0

我有以下方法来检索 logback 在日志目录中生成的日志文件的名称。前 9 行确定日志记录目录:

    private List<String> getLogFileNames() {
        List<String> logFileNames = new ArrayList<>();

        ch.qos.logback.classic.Logger rootLogger = ((ch.qos.logback.classic.Logger) LOGGER).getLoggerContext().getLogger("root");

        Path logDir;

        Appender<ILoggingEvent> appender = rootLogger.getAppender("file");
        if (appender == null) {
            logDir = Paths.get(System.getProperty("user.dir"), "../logs");
        } else {
           RollingFileAppender<?> rollingFileAppender = (RollingFileAppender<?>) appender;
           logDir = Paths.get(rollingFileAppender.getFile()).getParent();
       }

        try {
            Files.list(logDir).forEach(log -> logFileNames.add(log.toFile().getName()));
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }

        return logFileNames;
}

有时会抛出以下异常: java.nio.file.FileSystemException: ... : Too many open files

我怀疑在 Files.list(logDir).forEach() 语句中引发了异常。不知何故,在这段代码中,文件被打开但从未关闭。我应该如何解决这个问题?我可以使用 foreach 语句还是应该使用类似的语句:

try(Stream<Path> stream = Files.walk(logDir)) {
    // Code to extract the filename
}
catch(UncheckedIOException ex) {
    throw ex.getCause();
}
4