Junjao

Programming, Software Engineering

แปลงจากไฟล์ที่เข้ารหัสเป็น UTF-8 เป็น TIS-620 ตุลาคม 3, 2011

Filed under: Uncategorized — จั่น @ 7:53 pm

เป็นตัวอย่าง code การแปลงจากไฟล์ที่มีภาษาไทย เข้ารหัสด้วย UTF-8 (ภาษาไทยแต่ละตัวใช้พื้นที่ 3 bytes)
—-> แปลงเป็นไฟล์ที่มีภาษาไทย เข้ารหัสด้วย TIS620  โดยภาษาไทยแต่ละตัวใช้พื้นที่เหลือ 1 byte

static String readInput() {

    StringBuffer buffer = new StringBuffer();
    try {
        FileInputStream fis = new FileInputStream("test.txt");
        InputStreamReader isr = new InputStreamReader(fis,"UTF8");
        Reader in = new BufferedReader(isr);
        int ch;
        while ((ch = in.read()) > -1) {
                buffer.append((char)ch);
        }
        in.close();
        return buffer.toString();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
static void writeOutput(String str) {

    try {
        FileOutputStream fos = new FileOutputStream("test2.txt");
        Writer out = new OutputStreamWriter(fos, "TIS620");
        out.write(str);
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

วิธีการทดสอบ
1.สร้างไฟล์ test.txt ที่มีภาษาไทย เข้ารหัสด้วย UTF-8  แล้วเปิดดูแบบ hex viewer ด้วย EditPlus จะเห็นว่าภาษาไทยแต่ละตัวใช้ 3 bytes
2.รันโปรแกรม ทดสอบ
3.แล้วเปิด test2.txt แบบ hex viewer ด้วย EditPlus จะเห็นว่าภาษาไทยแต่ละตัวใช้ 1 byte

อ้างอิง

http://download.oracle.com/javase/tutorial/i18n/text/stream.html

 

ใส่ความเห็น

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / เปลี่ยนแปลง )

Twitter picture

You are commenting using your Twitter account. Log Out / เปลี่ยนแปลง )

Facebook photo

You are commenting using your Facebook account. Log Out / เปลี่ยนแปลง )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.