1

I wrote the code below, it can not read the file utf-8. I've tried to search for documents online, but I can not be corrected.

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

}

//in main class:

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

    }
}

file 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

Smit
  • 4,685
  • 1
  • 24
  • 28
taki
  • 75
  • 1
  • 10

2 Answers2

4
new FileReader(fileName)

As indicated in the documentation:

The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.

So, if your file is encoded using UTF-8, and your default encoding is not UTF-8, that won't work. The documentation explains what must be done in this case:

new InputStreamReader(new FileInputStream(fileName), "UTF-8")
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

Try this:

BufferedReader in = new BufferedReader(
  new InputStreamReader(new FileInputStream(fileName), "UTF-8"));
Chaos
  • 11,213
  • 14
  • 42
  • 69