简体   繁体   中英

Reading unicode text in Java and display on JLabel?

I have the following code reading a file containing unicode text (Japanese).

File f = new File("f.txt"); // the file was saved with utf-8 encoding
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);

s = br.readLine();
lblData.setText(s); // JLabel lblData was set font as Tahoma

br.close();
fr.close();

Im using window 7 and the system already installed Japanese font (MSMINCHO.TTF).

If I run the above code in Netbeans (6.9) editor then the program display correctly.

But when I exported to jar file and run the program independently of Netbeans, then it is no longer displaying correctly.

I dont know why this happened and how to fix it?

Use FileInputStream and initialise the reader like this:

br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), Charset.forName("UTF-8")));

that will give you the characters correct from the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM