基础测试题中有一个要求复制文件的题,我写的时候,用了一个文本文件测试的,发现复制后的文件可以看,今天我用了一个Mp3文件实验,结果,写了几个方法,新复制出来的文件都不能打开了。这是怎么回事?还有就是,复制出来的文件比原文件都小一些。
我的四个方法如下:
方法一:
public void copy1 (File from, String to) throws IOException, FileNotFoundException {
int read;
InputStreamReader isr = new InputStreamReader (new FileInputStream (from));
FileWriter fw = new FileWriter (to);
while ((read = isr.read()) != -1) {
fw.write(read);
}
fw.flush();
fw.close();
}
方法二:
public void copy2 (File from, String to) throws IOException, FileNotFoundException {
BufferedReader br = new BufferedReader (new FileReader (from));
FileWriter fw = new FileWriter (to);
//BufferedWriter bw = new BufferedWriter (fw);
String read = new String();
while ((read = br.readLine()) != null) {
fw.write(read);
}
fw.flush();
fw.close();
}
方法三:
public void copy3 (File from, String to) throws IOException, FileNotFoundException {
BufferedReader br = new BufferedReader (new FileReader (from));
FileWriter fw = new FileWriter (to);
BufferedWriter bw = new BufferedWriter (fw);
String read = new String();
while ((read = br.readLine()) != null) {
bw.write(read);
}
bw.flush();
bw.close();
}
方法四:
public void copyEfi3 (File from, String to) throws IOException, FileNotFoundException {
BufferedReader br = new BufferedReader (new FileReader (from));
//FileWriter fw = new FileWriter (to);
BufferedWriter bw = new BufferedWriter (new FileWriter (to));
String read = new String();
while ((read = br.readLine()) != null) {
bw.write(read);
}
bw.flush();
bw.close();
}
|