编写程序TextFileCopy.java,在测试方法中,将TextFileCopy.java复制为TextFileCopy.java.bak文件; 查看TextFileCopy.java.bak文件的内容,验证复制是否正确。
package com.xatu.IO;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
public class TextFileCopy {
public static void main(String[] args) {
Reader fr = null;
Writer fw = null;
try {
fr = new FileReader("TextFileCopy.java");
fw = new FileWriter("TextFileCopy.java.bak");
char[] cbuf = new char[100];
int realChars = 0;
while ((realChars = fr.read(cbuf)) != -1) {
fw.write(cbuf, 0, realChars);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(fr != null)
try {
fr.close();
} catch (Exception e) {
e.printStackTrace();
}
if(fw != null)
try {
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
换成字节流可以复制音视频文件
package com.xatu.IO;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class BinFileCopy {
public static void main(String[] args) {
InputStream frs = null;
OutputStream fws = null;
try {
frs = new FileInputStream("01_.avi");
fws = new FileOutputStream("01_副_.avi");
byte[] b = new byte[100];
int realCharBin = 0;
while ((realCharBin=frs.read(b)) !=-1) {
fws.write(b,0, realCharBin);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(frs != null)try {
frs.close();
} catch (IOException e) {
e.printStackTrace();
}
if(fws != null)try {
fws.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}