0

I'm taking some files from different folders in Java as below:

    File d=new File(path); // Path here is surely not null
    String s[]=d.list(); 
    System.out.println("Directory: "+path+s[0]+"/");

Above code works in Eclipse and my OS is Ubuntu 14.04. When I compile and run the project from terminal, I get the following error:

Exception in thread "main" java.lang.NullPointerException
at io.ReadFile.read2Dir(ReadFile.java:97)
at io.ReadFile.readDir(ReadFile.java:134)
at gui.Run.readFile(Run.java:35)
at gui.Run.main(Run.java:304)

Even if s[0] corresponds to a folder, I get NullPointerException in terminal.

This is how I compile from terminal:

javac -sourcepath src -cp /home/myUsername/workspace/tezoz_my/ -encoding ISO-8859-1 src/gui/Run.java

By the way, I had to change encoding because project is created with ISO 8859-1.

Then I run the project: java gui.Run

This is where the error occurs: System.out.println("Directory: "+path+s[0]+"/");

Thanks.

Kerem
  • 1,244
  • 2
  • 11
  • 24

1 Answers1

2

If the exception occurs on one of the three lines shown, then I suspect that the problem occurs on this line:

   System.out.println("Directory: "+path+s[0]+"/");

because s is null.

The javadoc for File.list() says:

Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.

So, I surmise that this is happening because path contains a pathname1 that either resolves to a file (not a directory), to a directory that cannot be read, or to nothing at all. (There are other, more obscure possibilities too)


1 - If you did mistakenly try to use a URL, the code would attempt to resolve it as if it was a pathname. For example "http://example.com/index.html" would refer to something in a directory whose name is "http:" which is highly unlikely to exist. (Colon is a legal character in a filename on most modern operating systems ... though apparently not on Mac OSX.)

Stephen C
  • 669,072
  • 92
  • 771
  • 1,162
  • I finally found what's the problem. In order to get the current directory, I was using `System.getProperty("user.dir")`. The silly mistake is I run the project in `/src` directory from the terminal. But my file is in the root directory of the project. Took the file in src folder and it worked. – Kerem Mar 20 '16 at 10:53