废话不多说 先看程序,解释在下面
这是一段统计一段文字中每个字出现的个数,在输出到文件时出现 数字乱码
@Test
public void test() throws IOException, InterruptedException {
File file=new File("hello");
File fw= new File("hellow.txt");
FileReader fr=new FileReader(file);
FileWriter writer=new FileWriter(fw);
int data;
HashMap<Character,Integer> map=new HashMap();
while((data=fr.read())!=-1){
//containsKey();判断是否存在key
if(map.containsKey((char)data)){
map.replace((char) data,(map.get((char)data)+1));
continue;
}
map.put((char)data,1);
}
map.forEach((key,value)->{
System.out.println((char)key +" "+value);
});
map.forEach((key,value)->{
try {
writer.write(key);
writer.write(" = ");
writer.write(value);
} catch (IOException e) {
e.printStackTrace();
}
});
fr.close();
writer.close();
}
在上面我们在程序中打印了map发现并没有问题 所以问题出现在FileWriter 这种查错思路个人感觉还是很不错的*
然后我们查看FileWriter 的源码部分
/**
* Writes a single character.
*
* @exception IOException If an I/O error occurs
*/
public void write(int c) throws IOException {
se.write(c);
}
在进入StreamEncoder(se)的 write()中查看
public void write(int var1) throws IOException {
char[] var2 = new char[]{(char)var1};
this.write((char[])var2, 0, 1);
}
我们不难发现 在其源代码中write写入的其实还是一个char型只有两个字节而int有4个字节 所以如果直接输入整形可能就会存在乱码问题
在输入到文件时不妨吧整形转为char 或者字符串
writer.write(String.valueOf(value));
writer.write(value+"");
如果对您有所帮助 希望留下你来过的痕迹(嘿嘿当然是点个赞啦)