-1

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.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Jack English
  • 107
  • 2
  • 9
  • 1
    And if you run `System.out.println(System.getProperty("user.dir"));` what is returned? And what is the relative path of your file to the user directory path? – Hovercraft Full Of Eels Aug 24 '14 at 00:39
  • if the assets dir is next to src then the relative would be ../assets/test.txt (assuming by "next to" you mean in the same parent directory) – radar Aug 24 '14 at 00:45
  • it goes to the project workspace and the test.txt is in bin so I changed the path to bin/test.txt and that solved it. Thanks – Jack English Aug 24 '14 at 01:32

2 Answers2

0

Just use (without starting slash):

try {
  string = readFile("assets/test.txt",Charset.defaultCharset());
} catch (IOException e) {
  e.printStackTrace();
}

To get path relative to project root.

Dejan Pekter
  • 705
  • 3
  • 18
0

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.

eckes
  • 10,103
  • 1
  • 59
  • 71