jdk1.7以上有文件复制方法直接用
import java.nio.file.Files;
private static void copyFileTest(File oldFile, File newFile) {
try {
Files.copy(oldFile.toPath(), newFile.toPath());
} catch (IOException e) {
e.printStackTrace();
}
}
使用Apache Commons IO包中的FileUtils.copyFile方法复制
import org.apache.commons.io.FileUtils;
private static void copyFileTest(File oldFile, File newFile) {
try {
FileUtils.copyFile(oldFile, newFile);
} catch (IOException e) {
e.printStackTrace();
}
}
文件通道(FileChannel)来实现文件复制
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel;
public static void copyFileTest(File oldFile, File newFile) {
if(!newFile.getParentFile().exists())//判断有没有父路径,就是判断文件整个路径是否存在
newFile.getParentFile().mkdirs();//不存在就全部创建
FileOutputStream fo = null;
FileInputStream fi = null;
FileChannel out = null;
FileChannel in = null;
try {
fo = new FileOutputStream(newFile);
fi = new FileInputStream(oldFile);
in = fi.getChannel();
out = fo.getChannel();
/*ByteBuffer bb;
bb = in.map(MapMode.READ_ONLY, 0,in.size()).load();
out.write(bb);*/
in.transferTo(0, in.size(), out);//从in读取,然后写入out。前三行注释的代码也可以直接复制
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
fi.close();
in.close();
fo.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}