本文通过Java的I/O接口实现文件在电脑磁盘内的复制。仔细观察会发现,该程序复制文件的速度要远远比系统复制文件的速度慢,可能是由于系统在磁盘内复制是地址的发送过程,而该程序采用了输入、输出流完全抄写的方法。
import java.io.File;//文件类
import java.io.FileInputStream;//文件的输入流
import java.io.FileOutputStream;//文件的输出流
import java.io.FileNotFoundException;//文件未找到时的报错
public class Test {
String IPath;//源文件地址
String OPath;//目标文件地址
char c;
public static void main(String[] args) {
String IPath = "D:/Penguins.jpg";
String OPath = "D:/Penguins2.jpg";
Test test = new Test();
test.saveFile(IPath, OPath);
}
public void saveFile(String IPath, String OPath) {
this.IPath = IPath;
this.OPath = OPath;
File Ifile = new File(IPath);
File Ofile = new File(OPath);
try {
FileInputStream fis = new FileInputStream(Ifile);
FileOutputStream fos = new FileOutputStream(Ofile);
for(int i=0; i<Ifile.length(); i++) {
c = (char) fis.read();
fos.write(c);
}
//输入流和输出流在使用后一定要记得关闭,否则可能造成复制时目标文件体积不断增大的后果。
fis.close();
fos.close();
//Eclipse的辅助功能会选用其他的报错类,这里将它们统一为Exception。
} catch (Exception e) {
e.printStackTrace();
}
}
}