2015-09-20 65 views
0

我创建了一个使用File.delete()方法删除文件的迷你程序,但如果我使用缓冲阅读器读取.txt文件时遇到了一点问题在我删除它之前,它不会删除该文件。我确实想出了一个解决方案:在删除文件之前,我只关闭了缓冲读取器。然而,这对我来说没有任何意义,为什么会出现这种情况,任何人都可以解释这一点。缓冲阅读器和file.delete

import java.io.*; 
import java.nio.file.Files; 

public class Purge { 

    public static void main(String[] args) throws IOException { 
     // TODO Auto-generated method stub 

     String sample; 
     boolean result = false; 


     BufferedReader amg = new BufferedReader(new FileReader("C:/Users/Steven/Desktop/me.txt")); 
     sample = amg.readLine(); 
     amg.close();// closes the buffered reader 
       System.out.println("Haha I'm stille here: "+sample); 
     File anesu = new File("C:/Users/Steven/Desktop/me.txt"); 

     if (anesu.exists()){ 

     try{result = anesu.delete(); 

     }catch(Exception x){ 
      System.out.println("Problem Deleting File"+x); 
     } 
     catch(Throwable e){ 
      System.out.println("Problem Deleting File Throwable"+e); 
     } 

     }else{ 
      System.out.println("No File "); 
     } 
     System.out.println("File has been deleted: "+result); 

    } 

} 
+0

我不确定文件锁定行为java(或windows),但删除一个被“BufferedReader”打开的文件(可能仍在使用)将被另一个File对象删除没有错误?它通常期望您在尝试删除它们之前关闭所有文件。 – shanmuga

+0

这里没有任何意义的是试图删除一个你仍然可以阅读的文件。下决心是否尝试读取文件或将其删除。你不能同时做两个。 – EJP

回答

0

当一个流对象被垃圾收集时,它的终结器关闭了底层的文件描述符。因此,删除仅在您添加System.gc()调用时才有效,这一事实证明您的代码无法关闭某个文件流。它可能与您发布的代码中打开的流对象不同。

注:

写得恰当流处理代码使用finally块来确保数据流得到不管关闭。

如果你不希望使用System.gc()的,阅读你的内容用的FileInputStream

InputStream in = new FileInputStream(new File("C:/temp/test.txt")); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 
    StringBuilder out = new StringBuilder(); 
    try { 
     String line; 
     while ((line = reader.readLine()) != null) { 
      out.append(line); 
     } 
     System.out.println(out.toString()); //Prints the string content read from input stream 
    } 
    catch(Exception ex) {//TODO} 
    finally { 
     reader.close(); 
    } 
0

您可以删除该文件中的finally块。 这种方法的缺点是,如果抛出异常,文件仍然会被删除。

public Stream<String> readLines(Path archive) { 
     try { 
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
        (new FileInputStream(archive.toFile())))); 

      return bufferedReader.lines(); 
     } catch (IOException e) { 
      throw new UncheckedIOException(e); 
     } finally { 
      try { 
       Files.delete(archive); 
       System.out.println("Deleted: " + archive); 
      } catch (IOException e) { 
       System.out.println("Unable to delete: " + archive); 
      } 
     } 
    }