[英]Unable to read from file in java even though file is in working directory
[英]DirectoryStream is empty, even though there is a file in the directory
我有DirectoryStream的問題。 我目前正在嘗試為我的應用程序構建一個LogViewer,它應該遍歷目錄中的所有Files並將它們添加到Grid中。
出於測試目的,它目前只包含一個文件。
這是代碼:
final Path logDirPath = Paths.get(this.logDir);
if (logDirPath.toFile().isDirectory()) {
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(logDirPath, "*.log")) {
for (Path p : directoryStream) {
logFiles.add(new LogFile(p.toFile()));
}
} catch (final IOException e) {
this.logger.error("Could not read files in directory {}", this.logDir, e);
}
}
logDir
的值是logs/activity
。
我試過調試它,但它只是跳過了行logFiles.add(new LogFile(p.toFile()));
,所以看起來目錄必須是空的,但我知道它不是。
那么,有人能發現問題嗎? 任何幫助將不勝感激。
編輯
我通過了logDir
@Value("${logging.directory}")
private String logDir;
來自application.properties
文件,看起來像
logging.directory=logs/activity
logging.file=${logging.directory}/activity.log
但是,我不認為它與此有任何關系,因為我已經嘗試通過簡單地硬編碼logs/activity
替換logDir
。
您可以使用文件訪問者。 無論如何,這樣更安全,因為在訪問結束時保證釋放所有資源。 此外,它還提供了自定義如何迭代文件系統所需的每個入口點。
Files.walkFileTree(Paths.get("logs/activity"), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.endsWith(".log")) {
// Handle log file.
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
// Handle exception
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
// CONTINUE if you want recursive behaviour, SKIP_SUBTREE if not.
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});
現在解決了這個問題:我只是沒有將logFiles列表添加到Grid中。
是什么讓我認為DirectoryStream
是空的是錯誤,是調試器跳過for循環。 我想這就是eclipse調試器如何處理它。
我之前使用過IntelliJ,我很確定他們的調試器不會處理它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.