从文件读取特殊字符时发出 [英] Issue while reading special characters from file

查看:296
本文介绍了从文件读取特殊字符时发出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读具有特殊字符的文件时遇到问题。我的.txt文件有数据:



我正在阅读这个文件,使用下面的代码:

  StringBuilder sBuilderString = new StringBuilder(); 

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





$ b

这个字符串现在又用来写一个文件了,问题是当我写的文件,这两个字符之一被替换为一些其他的特殊字符。

如何编写代码,它能够读取所有的特殊字符,并写那到另一个文件?

解决方案

您的字符编码有问题。对'(char)n)的调用将使用系统的默认字符编码将字节n有效地转换为字符,这可能与源文件的编码不同。



<避免这种情况的一种方法是将InputStream包装在CharacterInputStream中,您可以在其中指定字符编码:

 读卡器= new InputStreamReader(loInputStream,UTF-8); 

然后你可以继续阅读你的StringBuilder。我还建议使用bufferedReader封装您的阅读器,以提高阻止IO流的性能。

 阅读器阅读器=新的BufferedReader InputStreamReader(loInputStream,UTF-8)); 


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

这篇关于从文件读取特殊字符时发出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆