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 ストリームを拡張する 2 番目のクラス

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

1 に答える 1