Ok. I have the following web app snippet (called in constructor - if that is important):
private File[] logFiles;
...
try {
File directory = new File(auditDirectory);
LOG.debug("Found directory: " + directory.getAbsolutePath());
logFiles = directory.listFiles();
LOG.debug("Number of logFiles: " + logFiles.length);
} catch (Exception e) {
LOG.error("Exception: ", e);
throw new RuntimeException("Failed to get list of audit files", e);
}
In my windows environment (localhost) everything works like a charm. After deployment on linux (ubuntu) environment, seems that line
directory.listFiles();
returns null value. I have concluded that from the following linux deployment log:
c.a.s.a.a.AuditFileSource - Found directory: /home/myapp/myappfolder/logs
c.a.s.a.a.AuditFileSource - Exception:
java.lang.NullPointerException: null
at com.myapp.services.administration.audit.AuditFileSource.<init>(AuditFileSource.java:31) ~[com.myapp.services-2.2.2.jar:2.2.2]
at...
Log line AuditFileSource.java:31 is actually the line:
LOG.debug("Number of logFiles: " + logFiles.length);
and it is obvious that NullPointerException is raised as an attempt to access lenght on logFiles variable which is null.
My first try was to change permissions on relevant Linux folders but they already have read permissions. I'm completely puzzled. Any Idea?
That's one of the numerous problems with File
; its .listFiles()
method is unreliable.
Try and use this instead:
final Path dir = Paths.get("path/to/directory");
final DirectoryStream<Path> dirStream = Files.newDirectoryStream(dir);
// use the stream
If the fs entry is not a directory, you'll at least get a NotDirectoryException
; if you don't have enough permissions, you'll get an AccessDeniedException
; etc etc.
Drop File
. This is 2015, after all. And the new file API (aka JSR 203, aka NIO2) has been there since 2011!
Since Java 8 you can also use Files.list()
; DO NOTE however that you SHOULD use it in a try-with-resources block like this:
try (
final Stream<Path> stream = Files.list(thedir);
) {
// use the stream
}
It is a little known fact that Stream
(well, BaseStream
in fact) implements AutoCloseable
!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With