I'm running an java application that needs to read a text file and save it to a string but I keep getting a NoSuchFileException
. The text file is in a folder next to src called assets.
static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
This is the method that reads the file that I found on here.
try {
string = readFile("test.txt",Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
}
I've tried "/assets/test.txt" and other variations also to no avail.
If you execute a Java program from within Eclipse the typical run configuration will put the project's base directory as the current work directory of the Java process. So you need to use a relative path based on that directory (assets/test.txt
or src/main/assets/test.txt
or similiar). You can also use the full path (example: /somewhere/workspace/project/assets/test.txt
).
You can always use System.out.println("CWD=" + new File(".").getAbsolutePath());
to query the directory the Java runtime thinks it is started in.