Trong bài viết này, tôi sẽ hướng dẫn các bạn cách để đọc file có nội dung tiếng việt UTF-8 trong Java.
Một file có nội dung như sau:
Dưới đây là ví dụ để chứng minh làm thế nào để đọc dữ liệu được mã hoá “UTF-8” từ một file trong Java:
package com.itphutran.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 Test{ public static void main(String[] args){ try { File fileDir = new File("c:\\temp\\test.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()); } } }
Kết quả:
Một buổi chiều! A nhớ e!