This recipe shows how to load the file from the resource folder and receive it's content as a
We could receive proper
String.
Project structure
|--src | \--main | \--java | \--resources | |--lines.json
Get file path from resources folder
In order to receive the resource with given name we need to usejava.lang.ClassLoader:
ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL url = loader.getResource(filename);
Path replaces File for a representation of a file or directory.Paths.get() lets you create a Path object.
Path instance from URL via Paths.get(uri) method:
Path path = Paths.get(loader.getResource(filename).toURI());
Whatchout: if you will use
Using the paths above might cause
loader.getResource(name).getPath() or .getPath()it'd return url with leading /
/C:/my-project/target/classes/lines.jsonVia using
.toString() output would be: file:/C:/my-project/target/classes/lines.json
Using the paths above might cause
nio.file.InvalidPathException.
Read file as a String
JDK7
You can use the methods in the
Files API methods work on instances of Path objects.You can use the methods in the
File class to check the existence of the file corresponding to the Path, create the file, open it,
delete it, change its permissions, and so on.
Using Buffered I/O is more efficient, since the native API is called only when buffer is empty, instead of triggering expensive operations
(disk access, network activity, etc.) each time.
public String readFileAsString(String filename) throws URISyntaxException {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Path path = Paths.get(loader.getResource(filename).toURI());
try(BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
System.out.println("Read texts from file text:" + sb.toString());
return sb.toString();
} catch (IOException e) {
System.out.println("Error: Could not read file: " + e.toString());
}
return null;
}
No comments:
Post a Comment