我有以下方法来检索由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:...:打开的文件太多
我怀疑在Files.list(logDir).forEach()语句中引发了异常。这段代码文件以某种方式被打开但从未关闭。我该如何解决?我可以使用foreach语句还是应该使用类似的内容:
try(Stream<Path> stream = Files.walk(logDir)) {
// Code to extract the filename
}
catch(UncheckedIOException ex) {
throw ex.getCause();
}