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

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

Nội dung fileWrite3.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 AppendContentFileWIthOutputStreamWriter.java

package com.loop.io;

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

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

Kết quả fileWrite3.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 fileWrite4.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 AppendContentFileWIthOutputStreamWriterTryWithResouce.java

package com.loop.io;

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

public class AppendContentFileWIthOutputStreamWriterTryWithResouce {
  /**
  *
  * Create by Cuder
  */
  public static void main(String[] args) {
    try (OutputStreamWriter out = new OutputStreamWriter(
      new FileOutputStream("resource/fileWrite4.txt", true), "UTF-8");) {
      for (int i = 0; i < 10; i++) {
        out.write("line content : " + (i + 1) + "\n");
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Kết quả fileWrite4.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