Search code examples
javafileutf-8character-encodingjtextfield

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?

Many thanks!


Solution

  • 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));