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.
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:
Java says it doesn't exist! The javadocs say that
Files.list()returnsnullif the object denoted by the pathname does not exist, is not readable, or is not a directory.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
downloaddirectory 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
FilesandPathAPIs rather than the legacyFileAPI. 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.