读取和删除文件

时间:2013-04-03 06:03:46

标签: java fileinputstream

我尝试过类似下面的内容来编写文件,阅读并删除。 这是最好的方式吗?

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

1 个答案:

答案 0 :(得分:2)

当您读取文件时,请使用缓冲区以获得更高的效率。

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

希望能帮到你。

相关问题