RT
package com.test2;
import java.io.*;
public class TestDemo {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File a=new File("d:\\test","aaa.txt");
a.createNewFile();
FileOutputStream CC=new FileOutputStream(a);
String str="文件复制";
byte[] bb=str.getBytes();
CC.write(bb);
FileReader rea=new FileReader(a);
int c1=rea.read();
File b=new File("d:\\test2","bbb.txt");
b.createNewFile();
FileWriter wri=new FileWriter(b);
while(c1!=-1)
{
wri.write(c1);
}
}
}
------解决方案--------------------
while(c1!=-1)
{
wri.write(c1);
}
这明显是个无限循环
------解决方案--------------------
int c1;
while((c1=rea.read())!=-1)
{
wri.write(c1);
}
这样就没问题了吧
------解决方案--------------------
- Java code
public static void main(String[] args) throws IOException { File a = new File("d:\\aaa.txt"); a.createNewFile(); FileOutputStream CC = new FileOutputStream(a); String str = "文件复制"; byte[] bb = str.getBytes(); CC.write(bb); FileReader rea = new FileReader(a); File b = new File("d:\\bbb.txt"); b.createNewFile(); FileWriter wri = new FileWriter(b); int c1; while((c1 = rea.read()) != -1) { System.out.println(c1); wri.write(c1); wri.flush(); } }
------解决方案--------------------
错误一:while(c1!=-1){......} 语句跳不出循环,因为c1是不可能等于-1的。
错误二:rea.read()一次只能读出一个字节,中文每个字占两个字节。所以会出乱码。而英文每个字母一个字节。
如果是单纯的为了实现文件复制,可以用下面的代码段来实现
- Java code
import java.io.*;import java.util.Scanner;public class dd{ static Scanner tc=new Scanner(System.in); public static void main(String arg[]) throws IOException{ File f1=new File("1.txt");//改成你的文件路径和名字 File f2=new File("2.txt");//实现复制新文件 /*实现覆盖:File f2=new File(f1);*/ FileWriter fw=new FileWriter(f2); Scanner tc=new Scanner(f1); while(tc.hasNextLine()){ fw.write(tc.nextLine()+"\r\n"); tc.hasNextLine(); } fw.close(); }}