这段简单的io程序,为什么没有达到效果呢?

samyp1234 2010-03-04 02:49:58
在D盘上有3.txt文件,内容如下:
1,张三
2,李四
3,AA
4,BB



想通过程序,生成一个新的文件4.txt,内容为:
1张三
2李四
3AA
4BB

就是把3.txt中的,所有的逗号都去掉。但是下面的代码没有达到这个效果。


代码如下:

public void rep(){
try{
File file1 = new File("d:\\3.txt");
File file2 = new File("d:\\4.txt");
if(!file2.exists())
file2.createNewFile();
FileReader reader = new FileReader(file1);
FileWriter writer = new FileWriter(file2);
int a;
char b;
while( (a=reader.read())!=-1 ){
b = (char)a;
if(!( b == ',')){
writer.write(a);
}
}

}catch(IOException ex){
ex.printStackTrace();
}catch(Exception ex){
ex.printStackTrace();
}
}


请问大家:这是什么原因呢?

非常谢谢大家。
...全文
84 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
星辰企业 2010-03-04
  • 打赏
  • 举报
回复
其实就是写入流没有进行关闭! 关闭一下就OK了!!

示例代码如下!
package com.wsb.test;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileCopyChangeContext {

public static void main(String[] args){
try {
File file1 = new File("d:\\3.txt");
File file2 = new File("d:\\4.txt");
if (!file2.exists())
file2.createNewFile();
FileReader reader = new FileReader(file1);
FileWriter writer = new FileWriter(file2);
int a;
char b;
while ((a = reader.read()) != -1) {
b = (char) a;
if (!(b == ',')) {
writer.write(a);
}
}
reader.close();
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}


运行后4.txt的内容为:


1张三
2李四
3AA
4BB
bayougeng 2010-03-04
  • 打赏
  • 举报
回复
reader.read()返回的是字符么?如果是字符的话,你认为汉字'张'会被解释成什么字符呢?
east_java 2010-03-04
  • 打赏
  • 举报
回复
水中影子 2010-03-04
  • 打赏
  • 举报
回复
IO文件流,用完记得close
ychzxx 2010-03-04
  • 打赏
  • 举报
回复
public void rep() {
try {
File file1 = new File("d:\\3.txt");
File file2 = new File("d:\\4.txt");
if (!file2.exists()) file2.createNewFile();
FileReader reader = new FileReader(file1);
FileWriter writer = new FileWriter(file2);
int a;
char b;
while ((a = reader.read()) != -1) {
b = (char) a;
if (!(b == ',')) {
writer.write(a);
}
}
writer.flush();
writer.close();
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
awusoft 2010-03-04
  • 打赏
  • 举报
回复
reader.close();
writer.close();

关闭一下流就好了
hbgzg3006 2010-03-04
  • 打赏
  • 举报
回复
reader 和writer都close一下。看看。

62,624

社区成员

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

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