File.listFiles()在Linux上不起作用

Fil*_*lip 2 java linux ubuntu web

好.我有以下Web应用程序片段(在构造函数中调用 - 如果这很重要):

    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);
    }
Run Code Online (Sandbox Code Playgroud)

在我的Windows环境(localhost)中,一切都像魅力一样.在linux(ubuntu)环境上部署之后,似乎就行了

directory.listFiles();
Run Code Online (Sandbox Code Playgroud)

返回null值.我从以下linux部署日志得出结论:

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... 
Run Code Online (Sandbox Code Playgroud)

日志行AuditFileSource.java:31实际上是行:

LOG.debug("Number of logFiles: " + logFiles.length);
Run Code Online (Sandbox Code Playgroud)

很明显,NullPointerException是作为尝试访问logFiles变量上的lenght而引发的,该变量为null.

我的第一次尝试是更改相关Linux文件夹的权限,但他们已经具有读取权限.我完全不解.任何的想法?

fge*_*fge 8

这是众多问题之一File; 它的.listFiles()方法不可靠.

请尝试使用此代码:

final Path dir = Paths.get("path/to/directory");

final DirectoryStream<Path> dirStream = Files.newDirectoryStream(dir);

// use the stream
Run Code Online (Sandbox Code Playgroud)

如果fs条目不是目录,你至少会得到一个NotDirectoryException; 如果你没有足够的权限,你会得到一个AccessDeniedException; 等等

下降File.毕竟这是2015年.自2011年以来,新的文件API(又名JSR 203,又名NIO2)已经存在!


从Java 8开始你也可以使用Files.list(); 请注意,您应该在try-with-resources块中使用它,如下所示:

try (
    final Stream<Path> stream = Files.list(thedir);
) {
    // use the stream
}
Run Code Online (Sandbox Code Playgroud)

这是一个鲜为人知的事实Stream(BaseStream事实上)实现了AutoCloseable!