2013-04-03 164 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))); 

希望能帮到你。