Skip to content

Instantly share code, notes, and snippets.

@jesselima
Created January 6, 2019 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesselima/b3cd8b5d71b516fca79ac6fc9ccfe55f to your computer and use it in GitHub Desktop.
Save jesselima/b3cd8b5d71b516fca79ac6fc9ccfe55f to your computer and use it in GitHub Desktop.
Read local json file and converts it to a String.
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