Created
January 6, 2019 21:51
-
-
Save jesselima/b3cd8b5d71b516fca79ac6fc9ccfe55f to your computer and use it in GitHub Desktop.
Read local json file and converts it to a String.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.io.FileReader; | |
import java.net.URISyntaxException; | |
import java.net.URL; | |
import java.util.Scanner; | |
/* How to use it: | |
1 - Create a ClassLoader instance | |
ClassLoader classLoader = this.getClass().getClassLoader(); | |
2 - Pass the ClassLoader object and the finleName.json as input. | |
String stringJson = FileReaderUtil.readFile(classLoader, "fileName.json"); | |
*/ | |
public class FileReaderUtil { | |
public static String readFile(ClassLoader classLoader, String fileName) { | |
String result = ""; | |
try { | |
URL resource = classLoader.getResource(fileName); | |
File f = new File(resource.toURI()); | |
Scanner in = new Scanner(new FileReader(f)); | |
StringBuilder b = new StringBuilder(); | |
while (in.hasNextLine()) { | |
b.append(in.nextLine()); | |
} | |
result = b.toString(); | |
} catch (FileNotFoundException e) { | |
e.printStackTrace(); | |
} catch (URISyntaxException e) { | |
e.printStackTrace(); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment