File.list() returns null in Java - Springboot

145 views Asked by At

I have the following code

File folder = new File("./src/main/resources/uploads");
LOGGER.info("Read folder - {}", folder.getName()); // prints uploads correctly
folder.setReadable(true, false);
folder.setWritable(true, false);
String[] directories = folder.list();
System.out.println(directories.length)// throws an NPE here.

My code works on my windows machine fine but fails with an NPE on my UNIX environment. Am I doing something wrong here?

I tried with and without the following code

folder.setReadable(true, false);
folder.setWritable(true, false);

Uploads is definitely a directory which I created manually. Besides, it works fine on my local machine.

Thanks in advance.

2

There are 2 answers

0
Stephen C On

There is little doubt that the root cause of the problem is the obvious one. The directory that you have told it to list does not exist ... on the execution platform ... with that relative pathname ... when resolved relative to the executing application's current directory.

There are a couple of clues as to why that would be:

  1. Java says it doesn't exist! The javadocs say that Files.list() returns null if the object denoted by the pathname does not exist, is not readable, or is not a directory.

  2. Your pathname appears to be specified relative to your project directory. When you attempt to run (say) the JAR for your application on a different machine, that project directory won't be there. And even if it is there, the chances are that you (or some other user) won't have cd'd to that directory before running your JAR.

Now I don't know for sure what the purpose of the download directory is. But putting it in the "/src/resources" tree is probably a mistake ... even on the development platform.

Why? Because the files in the "resources" tree will (typically) be incorporated into the JAR (or WAR or whatever) file generated by your build tool.


There is insufficient context in your question to give you the most appropriate solution. One alternative is to make the location of the downloads directory a configuration parameter that the person deploying or running your application can modify.

Also, it advisable to use the Files and Path APIs rather than the legacy File API. The former will throw exceptions with informative exception messages if something goes wrong. For example, the message for a failed "list" will tell you is the problem is that the path is incorrect, the object is not accessible or if it is not a directory. No guesswork required.

0
PuneethC99 On

Using ResourceLoader fixed the issue for me.