การเขียนข้อมู UTF-8 encoded ลงไฟล์ใน Java

ต่อไปนี้เป็นตัวอย่างการเขียนข้อมูลที่เป็น UTF-8 Encoded ลงไฟล์ "C:\\users\\nopphanan7\\WriteUTF-8-file.txt" ใน Java
ตัวอย่าง
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package demo.file;
 
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 WriteUTF8EncodedExample {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            File fileDir = new File("C:\\users\\nopphanan7\\WriteUTF-8-file.txt");
 
            Writer out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(fileDir), "UTF8"));
 
            out.append("ทดสอบการเขียนไฟล์  UTF-8").append("\r\n");
            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());
        }
    }
}
ผลลัพธ์ที่ได้คือ

หมายเหตุ : หากตัว editor ไม่รองรับ utf-8 ให้ตั้งค่า โดยไปที่ Window -> Preferences -> General -> Workspace : Text file encoding : utf-8 นะครับ

About Nop

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment