个人经历,Java的学习过程,一开始对IO不是太了解,关于file读取操作的类有FileInputStream,FileReader,RandomAccessFile等,不知道该用哪个,后来在网上查资料看到FileInputStream比较适合文件复制。写了一个简单的文件复制类:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author dingbiao
* @param File sourceFile
* @param File targetFile
* @time 2008-07-25 17:14
* @place nuesoft F3 308
*/
public final class FileCopy {
public void copy(File sourceFile, File targetFile)
{
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(sourceFile);
out = new FileOutputStream(targetFile);
byte[] buffer = new byte[2048];
int len = 0;
while((len = in.read(buffer)) != -1)
{
out.write(buffer, 0 ,len);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
in.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
思路是从原文件里读取缓冲区大小的字节,写入到目标文件里,使用write(buffer, 0 , len)而不用write(buffer)是防止多写入空白字节。