ตัวอย่าง
package demo.file;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class ReadUTF8EncodedExample {
/**
* @param args
*/
public static void main(String[] args) {
try {
File fileDir = new File("C:\\users\\nopphanan7\\UTF-8-file.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(fileDir), "UTF8"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.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());
}
}
}
ผลลัพธ์ที่ได้คือ
ทดสอบการอ่านไฟล์ UTF-8หมายเหตุ : ไม่ต้องไปกังวลหากมีลักษณ์ "???" นะครับ ที่เป็นเช่นนี้เพราะเครื่องมือแสดงผล(console) ไม่รองรับข้อมูล UTF-8 ครับ เราสามารถแก้ได้โดยให้ไปตั้งค่าที่ Window -> Preferences -> General -> Workspace : Text file encoding : UTF-8 นะครับ.

0 comments:
Post a Comment