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

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

Tạo class WriteNewFileWithBufferedWriter.java

package com.loop.io;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteNewFileWithBufferedWriter {
  /**
  *
  * Create by Cuder
  */
  public static void main(String[] args) {
    String outputFile = "resource/fileWrite1.txt";
    BufferedWriter bw = null;
    FileWriter fw = null;
    try {
      fw = new FileWriter(outputFile);
      bw = new BufferedWriter(fw);
      for (int i = 0; i < 10; i++) {
        bw.write("line content : " + (i + 1) + "\n");
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
      if (bw != null)
        bw.close();
      if (fw != null)
        fw.close();
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
}

Kết quả fileWrite1.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 WriteNewFileWithBufferedWriterTryWithResources .java

package com.loop.io;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteNewFileWithBufferedWriterTryWithResources {
  /**
  *
  * Create by Cuder
  */
  public static void main(String[] args) {
    String outputFile = "resource/fileWrite2.txt";
    try (BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile))) {
      for (int i = 0; i < 10; i++) {
        bw.write("line content : " + (i + 1) + "\n");
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Kết quả fileWrite2.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
Đinh Thế Hiển
 

Mình là người thích viết lách, chia sẻ các trải nghiệm trong cuộc sống. Thích thể thao đặc biệt là thể hình. Hãy kết nối với mình nhé.

Click Here to Leave a Comment Below 0 comments