0

My project structure is like this:

  • Project
    • App
      • x.java
    • files
      • file.txt
    • main.java

I want to access file.txt via x.java.. My code:

    File file = new File("file.txt");
    Scanner sc = new Scanner(file);
    while (sc.hasNextLine())
        out += sc.nextLine();
    if (out.isEmpty()) out = "NOTHING";

but gives me NullPointerException.

3 Answers3

0

If this file is supposed to be part of your app the way class files are (so, effectively read-only, an asset that you pack in with the rest. Think texture maps for games, or icons for user interfaces), use getResourceAsStream, as the resource in question may not even be a file (java projects tend to ship as jars, and an entry in a jar is not a file!).

If not, well, then figure out a way to get the full path info into your code, because it's not going to magically figure out that you have a dir structure with "App" and "files", which is non-standard. (the standard route is src/main/java/pkgname/Type.java for java files, and src/main/resources/pkgname/open.png for assets that just need to be there (don't need compiling).

If you set up a project in your favourite IDE according to this structure and configured using e.g. maven or gradle, then getResourceAsStream works during dev time, and also at runtime, even if the resource is inside the jar.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
0

Basically when you read the file "file.txt", you don't provide with an absolute path so the operating system will look for a file in the current directly. That is the one where your program started.

I get you didn't start the program in the folder "files" but in another folder like maybe the folder "Project". In that case the path to use would be "files/file.txt".

Nicolas Bousquet
  • 3,990
  • 1
  • 16
  • 18
0

I solved it !
First, I used

            File directory = new File("./");
            System.out.println(directory.getAbsolutePath());

to detect the whole path.. Then I appended the directory.getAbsolutePath() with the filename so it becomes directory.getAbsolutePath()+"file.txt"
I used the normal way to read a file by using the scanner and scanner.readLine() to read the file !
This answer

Has helped me