2013-04-03 215 views
1

我已經嘗試過類似下面的內容來編寫文件,閱讀並刪除文件。 這是最好的方法嗎?閱讀並刪除文件

public class WriteFileExample { 

private void createFile(String filename){ 
     FileOutputStream fop = null; 
     File file; 
     String content = "This is the text content"; 

     try { 

      file = new File(filename); 
      fop = new FileOutputStream(file); 

      // if file doesnt exists, then create it 
      if (!file.exists()) { 
       file.createNewFile(); 
      } 

      // get the content in bytes 
      byte[] contentInBytes = content.getBytes(); 

      fop.write(contentInBytes); 
      fop.flush(); 
      fop.close(); 

      System.out.println("Done"); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (fop != null) { 
        fop.close(); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

} 

private void readAndDeleteFile(String filename){ 
    try { 
      DeleteOnCloseFileInputStream fis = new DeleteOnCloseFileInputStream(new File(filename)); 

      System.out.println("Total file size to read (in bytes) : " 
        + fis.available()); 

      int content; 
      while ((content = fis.read()) != -1) { 
       // convert to char and display it 
       System.out.print((char) content); 
      } 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (fis != null) 
        fis.close(); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
     } 

    } 

    public static void main(String[] args) { 
     WriteFileExample exe = new WriteFileExample(); 

     exe.createFile("c:/mytestfile.txt"); 
     readAndDeleteFile("c:/mytestfile.txt"); 
    } 
} 

第二類擴展的FileInput流

public class DeleteOnCloseFileInputStream extends FileInputStream { 
    private File file; 
    public DeleteOnCloseFileInputStream(String fileName) throws FileNotFoundException{ 
     this(new File(fileName)); 
    } 
    public DeleteOnCloseFileInputStream(File file) throws FileNotFoundException{ 
     super(file); 
     this.file = file; 
    } 

    public void close() throws IOException { 
     try { 
      super.close(); 
     } finally { 
      if(file != null) { 
      file.delete(); 
      file = null; 
     } 
     } 
    } 
} 
+0

在您嘗試刪除文件時,爲什麼您必須將它讀入InputStream? –

+0

fop.flush()是多餘的,因爲fop.close()將無論如何刷新流。由於性能問題,使用BufferedWriter或BufferedReader進行寫入或從流中讀取是更好的選擇。 – Kishore

+0

這個問題應該發佈[這裏](http://codereview.stackexchange.com/users/23081/subodh) – subodh

回答

2

當你讀文件,使用緩衝區來獲得更高的效率。

InputStream is = BufferedInputStream(new FileInputStream(new File(fileName))); 

希望能幫到你。