Sử dụng BufferedWriter để thêm nội dung file trong Java

1. Thêm nội dung file sử dụng java BufferedWriter

Nội dung 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

Tạo class AppendContentFileWithBufferedWriter.java

package com.loop.io;

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

public class AppendContentFileWithBufferedWriter {
  /**
  *
  * 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, true);
      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
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. Thêm nội dung file sử dụng try datasource với JDK7

Nội dung 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

Tạo class AppendContentFileWithBufferedWriterTryWithResources.java

package com.loop.io;

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

public class AppendContentFileWithBufferedWriterTryWithResources {
  /**
  *
  * Create by Cuder
  */
  public static void main(String[] args) {
    String outputFile = "resource/fileWrite2.txt";
    try (BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile,true))) {
      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
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