Where to setCharSet() for display Strings from UTF-8 files on JPanel
I'm reading a UTF-8 encoded text file via a JFileChooser and access the file's contents via BufferedReader.readLine. The values are saved in Strings which I display in a JTextField. My question is: Where do I have to setCharSet() in the process in order to have special characters displayed properly?开发者_如何学Python
Many thanks!
You don't - you just load them in properly from the file in the first place. A java.lang.String
can represent anything in a UTF-8 file, admittedly using surrogate pairs where necessary. All you've got to do is make sure that you load your file properly (specify the encoding when you read the file) and check that your JTextField
uses a font which can display all the relevant characters.
You say that you're using BufferedReader.readLine
to read the file, but you haven't shown how you're creating the BufferedReader
to start with. You should probably use a FileInputStream
wrapped in an InputStreamReader
created specifying the right encoding (UTF-8 in this case), then wrapped in a BufferedReader
.
Encodings and character sets are needed when characters are stored as bytes in arrays or files. Java strings work with full Unicode characters (and so does JTextField
) and don't need any encoding or character set. So there is no need to set the character set in JTextField
.
The character set is however relevant when you read the file. You can initialize the correct readers with the following code:
Reader reader = new InputStreamReader(new FileInputStream(filename),"UTF-8");
BufferedReader br = new BufferedReader(reader));
精彩评论