为什么用BufferedWriter将int型写入文件后是乱码

yanghe0621 2010-06-08 02:09:03
public static void myWrite(MyTable table){
try{
FileOutputStream fos = new FileOutputStream("db.txt");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(table.name);
bw.newLine();
for(int i = 0;table.attribute[i] != null;i++){
bw.write(table.attribute[i].name);
bw.write(" ");
bw.write(table.attribute[i].flag1);//写入db.txt中是乱码
bw.write(" ");
bw.write(table.attribute[i].flag2);//写入db.txt中是乱码
bw.write(" ");
bw.write(table.attribute[i].flag3);//写入db.txt中是乱码
bw.newLine();
}
bw.flush();
bw.close();
}catch(IOException e){
System.err.println("文件输入有错误");
}
}
public class Attribute {
public String name;
public String value1;
public int value2;
public int flag1;
public int flag2;
public int flag3;
}
...全文
716 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Java技术栈 2010-06-08
  • 打赏
  • 举报
回复
乱码的原因是write并不是把int类型直接写入
而是把int类型转换成char类型的
如果想直接写入int型数字的就这样写write(Character.valueOf(数字))
非典型射手 2010-06-08
  • 打赏
  • 举报
回复
1楼是问题的根本,2楼是一个不错的解决方案
yanghe0621 2010-06-08
  • 打赏
  • 举报
回复
笨蛋 本来就是这样的。Attribute重写toString,
然后 bw.write(table.attribute[i].toString)就行了
qq84136264 2010-06-08
  • 打赏
  • 举报
回复
直接写Int型的话,用文本编辑器打开当然是乱码啊! 如果不想是乱码,把Int转成String类型,怎么转就不用说了吧 - -!

58,443

社区成员

发帖
与我相关
我的任务
社区描述
Java Eclipse
社区管理员
  • Eclipse
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧