简体   繁体   中英

How to write file path into txt.file?

I am writing simple program that is looking for file and if it exists, writes his path to txt file. If not, program is freezed for 1 minute. My problem is that file path is not being printed into txt file when searched file exists. I think it is something wrong with try block. I do not know where the problem is. How can i solve it?

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);
        }
    }
}

}

You should close the PrintWriter reference before finishing execution. It's an enforced practice to close a file after read/write on it.

If you are using Java +7 you can use the fancy way with try-with-resources syntax

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

With older versions you can use try-finally syntax

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

See

Java – Try with Resources

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM