帮你修改了一下代码。
你的问题有二。
一:流的打开和关闭应该注意先后顺序,“先打开后关闭,后打开先关闭”
先有fr,再有br。所以先关闭br,再关闭fr.
先有fw,再有bw。所以先关闭bw,再关闭fw.
二:流的读写应该注意异常后也要关闭,防止出现其他异常。就像下面我放到finally里面的。
public static void main(String[] args) throws IOException {
FileReader fr = null;
BufferedReader br = null;
FileWriter fw = null;
BufferedWriter bw = null;
try {
fr = new FileReader("D://myDoc//test.txt");
br = new BufferedReader(fr);
fw = new FileWriter("D://myDoc//test2.txt");
bw = new BufferedWriter(fw);
String line = br.readLine();
while (line != null) {
System.out.println(line);
bw.write(line);
line = br.readLine();
}
} finally {
bw.close();
br.close();
fw.close();
fr.close();
}
}
br.close();
fr.close();
bw.close();
fw.close(); 流关闭顺序有问题,再有判断结束的写法不对你写代码不标准啊,学习呢么
public static void main(String[] args) throws IOException
{
FileReader fr = new FileReader("D:/myDoc/test.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("D:/myDoc/test2.txt");
BufferedWriter bw = new BufferedWriter(fw);
String line = br.readLine();
while (line != null)
{
System.out.println(line);
bw.write(line);
line = br.readLine();
}
fr.close();
br.close();
bw.close();
fw.close();
}
这样应该就好了
while (line != null)
{
System.out.println(line);
bw.write(line);
line = br.readLine();
}
改成
while ( ( line = br.readLine())!= null)
{
System.out.println(line);
bw.write(line);
}
试试