เป็นตัวอย่าง 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