Sử dụng FileOutputStream để ghi file trong Java

1. Ghi file cơ bản sử dụng java FileOutputStream

Tạo class WriteNewFileWIthFileOutputStream .java

package com.loop.io;

import java.io.FileOutputStream;
import java.io.IOException;

public class WriteNewFileWIthFileOutputStream {
  /**
  *
  * Create by Cuder
  *
  */
  public static void main(String[] args) throws IOException {
    FileOutputStream fout = null;
    try {
      fout = new FileOutputStream("resource/fileWrite5.txt");
      for (int i = 0; i < 10; i++) {
        fout.write(("line content : " + (i + 1) + "\n").getBytes());
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (null != fout) {
        fout.close();
      }
    }
  }
}

Kết quả fileWrite5.txt

line content : 1
line content : 2
line content : 3
line content : 4
line content : 5
line content : 6
line content : 7
line content : 8
line content : 9
line content : 10

2. Ghi file sủ dụng try catch resource với JDK7

Tạo class WriteNewFileWIthFileOutputStreamTryWithResource.java

package com.loop.io;

import java.io.FileOutputStream;
import java.io.IOException;

public class WriteNewFileWIthFileOutputStreamTryWithResource {
  /**
  *
  * Create by Cuder
  *
  */
  public static void main(String[] args) throws IOException {
    try (FileOutputStream fout = new FileOutputStream("resource/fileWrite6.txt")) {
      for (int i = 0; i < 10; i++) {
        fout.write(("line content : " + (i + 1) + "\n").getBytes());
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Kết quả fileWrite6.txt

line content : 1
line content : 2
line content : 3
line content : 4
line content : 5
line content : 6
line content : 7
line content : 8
line content : 9
line content : 10

Rate this post
Click Here to Leave a Comment Below 0 comments