Làm thế nào để ghi một tập tin TXT có encoding là UFT-8? (How to write UTF-8 encoding data to TXT file in Java?)






Trong bài trước tôi đã hướng dẫn cách đọc một tập tin TXT có encoding là UTF-8, trong bài này tôi sẽ hướng dẫn cách tạo và ghi nội dung một tập tin TXT có encoding là UTF-8 trong Java.





Bạn lưu ý một số trình biên dịch hay trình hỗ trợ coding không hỗ trợ UTF-8 thì ghi ra file sẽ không hiển thị được kết quả mong muốn. Trình coding tôi đang sử dụng là Netbeans.

JavaWriteFileUTF8.java
/**
 * @(#)JavaWriteFileUTF8.java
 *
 * JavaWriteFileUTF8 application
 *
 * @author developer.bnson@gmail.com
 * @version 1.00 2014/3/17
 */

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

public class JavaWriteFileUTF8 {
   
    public static void main(String[] args) {
       
        try {
            File fileDir = new File("D:\\Z-Test\\VNLIVES_NET\\VN-Lives.txt");

            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileDir), "UTF8"));

            out.write("Welcome to my site VN-Lives");
            out.write("\r\n");
            out.write("Chào mừng bạn đến với site của tôi VN-Lives.");
           

            out.flush();
            out.close();

        } catch (UnsupportedEncodingException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } 
           
    }
}

Kết quả sau khi thực thi chương trình sẽ là:
























No comments:

Post a Comment