UTF-8でエンコードされたデータを含むテキストファイル


utf8 encoded file


P.Sファイルはこの記事のリンクで作成されています://java/how-to-write-utf-8-encoded-data-a-file-java/[UTF-8エンコードデータをファイルに書き込む方法]

ここでは、Javaのファイルから “UTF-8″エンコードデータを読み込む方法を示す例を示します

package com.mkyong;

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());
        }
    }
}

結果

Website UTF-8
?? UTF-8
??????? UTF-8

シンボル “???”を心配しないでください。これは、私の出力コンソールがUTF-8データをサポートしていないためです。変数 “str”は、テキストファイルに示されているものとまったく同じ “UTF-8″エンコードされたデータを格納しています。