简体   繁体   中英

Issue while reading special characters from file

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?

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

使用InputStreamReader并指定文件中使用的编码。

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