Issue while reading special characters from file

2019-07-28 01:14发布

问题:

I am facing an issue while reading a file with special characters. My .txt file has data:

I am reading this file using following code:

StringBuilder sBuilderString = new StringBuilder();

for (int n; (n = loInputStream.read()) != -1;) {
    sBuilderString.append((char)n);
}

This string is now again used to write a file, the issue is that when i write the file, one of these two characters is replaced by some other special character.

How can i write code, which is able to read all the special characters and write that to another file?

回答1:

You have issues with the encoding of your characters. The call to '(char) n) will effectively transform byte n into a character using the default character encoding of your system, which might differ from the encoding of your source file.

One way to avoid that is to wrap your InputStream in a CharacterInputStream, where you can specify the character encoding:

Reader reader = new InputStreamReader( loInputStream, "UTF-8");

You can then proceed to read your stream into your StringBuilder. I would also recommend to wrap your reader with a bufferedReader to improve performance with blocking IO streams.

Reader reader = new BufferedReader(new InputStreamReader( loInputStream, "UTF-8"));


回答2:

Use InputStreamReader and specify encoding which is used in the file.