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

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

Tạo class WriteNewFileWIthOutputStreamWriter.java

package com.loop.io;

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

public class WriteNewFileWIthOutputStreamWriter {
  /**
  *
  * Create by Cuder
  */
  public static void main(String[] args) throws IOException {
    FileOutputStream fout = null;
    OutputStreamWriter out = null;
    try {
      fout = new FileOutputStream("resource/fileWrite3.txt");
      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

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

Tạo class WriteNewFileWIthOutputStreamWriterTryWithResouce.java

package com.loop.io;

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

public class WriteNewFileWIthOutputStreamWriterTryWithResouce {
  /**
  *
  * Create by Cuder
  */
  public static void main(String[] args) {
    try (OutputStreamWriter out = new OutputStreamWriter(
      new FileOutputStream("resource/fileWrite4.txt"), "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

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