如何将文件路径写入txt.file



我正在编写一个简单的程序,该程序正在查找文件,如果存在,则将其路径写入txt文件。否则,程序将冻结1分钟。我的问题是,当搜索到的文件存在时,文件路径并没有打印到txt文件中。我认为try block有问题。我不知道问题出在哪里。我该怎么解决?

public class FileScanner {
public void scanFolder() throws IOException, InterruptedException {
Scanner input = new Scanner(System.in);
//tworzenie pliku logu
File log = new File("C:/Users/mateu/OneDrive/Pulpit/log.txt");
if (!log.exists()) {
log.createNewFile();
}
//obiekt zapisujacy nazwy i sciezki plikow do logu
PrintWriter printIntoLog = new PrintWriter(log);

while (true) {
//podanie sciezki szukanego pliku
System.out.println("Input file's directory you are looking for: ");
String path = input.nextLine();
//utworzenie obiektu do danego pliku
File searchedFile = new File(path);
//sprawdzenie czy plik istnieje- jesli tak to zapisuje do logu jego sciezke i usuwa go
try{
if (searchedFile.exists()) {
printIntoLog.println(searchedFile.getPath());
//searchedFile.delete();
}else{
throw new MyFileNotFoundException("Searching stopped for 1 minute.");
}
}catch(MyFileNotFoundException ex){
System.out.println(ex);
TimeUnit.MINUTES.sleep(1);
}
}
}

}

您应该在完成执行之前关闭PrintWriter引用。在读/写文件后关闭文件是一种强制的做法

如果你使用的是Java+7,你可以使用try-with-resources语法的奇特方式

```java
try (PrintWriter printIntoLog = new PrintWriter(log)) {
while (true) { 
....
}
}
```

对于旧版本,您可以使用try-finally语法

try {
while(true) {
...
}
} finally {
printIntoLog.close();
}

参见

Java–尝试使用资源

最新更新