1

我写了下面的代码,它无法读取文件 utf-8。我曾尝试在线搜索文档,但无法更正。

public List<Khach> readFile2(String fileName) {
        List<Khach> resultThue = new ArrayList<Khach>();
        try {
            BufferedReader reader = new BufferedReader(new FileReader(fileName));
            String line = reader.readLine();
            while (line != null) {
                String[] result = line.split(", ");

                Khach k = new Khach();
                k.setMaKhach(result[0]);
                k.setTenKhach(result[1]);
resultThue.add(k);
                line = reader.readLine();
}
            reader.close();
        } catch (FileNotFoundException e) {
            System.err.println(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultThue;
    }

}

//在主类中:

import java.util.List;

public class Program {
    public static void main(String[] args) {
        XuLyFile fp = new XuLyFile();
        List<Khach> rk = fp.readFile2("thue.txt");
        for (Khach k : rk) {
            System.out.println(k);
            System.out.println();
        }

    }
}

文件thue.txt:

K1, “Nguyễn A”, VIP:NOR,3,10, 5, M1-M3-M5

K2, “Nguyễn B”, VIP,2,15, 5, M1-M4-M5

K3, “Nguyễn C”, NOR,5,5, 5

K4, “Nguyễn D”, LOV,2,8, 5, M1-M2-M3

4

2 回答 2

4
new FileReader(fileName)

文档中所示:

此类的构造函数假定默认字符编码和默认字节缓冲区大小是适当的。要自己指定这些值,请在 FileInputStream 上构造 InputStreamReader。

因此,如果您的文件是使用 UTF-8 编码的,并且您的默认编码不是 UTF-8,那将不起作用。该文档解释了在这种情况下必须做什么:

new InputStreamReader(new FileInputStream(fileName), "UTF-8")
于 2013-10-04T16:56:28.610 回答
1

尝试这个:

BufferedReader in = new BufferedReader(
  new InputStreamReader(new FileInputStream(fileName), "UTF-8"));
于 2013-10-04T16:55:13.540 回答