java有两种文件流的
- 字符流:Reader/Writer
- 字节流:InputStream/OutputStream
如果文件不是普通的文本类型的话,就不能使用字符流了,所以通用的文件流还是字节流。这里使用字节流实现文件拷贝。
- 使用java.io.File中的方法
public static void copyByFileStreams(File source, File dest){
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try{
inputStream = new FileInputStream(source);
outputStream = new FileOutputStream(dest);
//一次性读入内存,再一次性写入
//byte[] b = new byte[(int)source.length()];
//inputStream.read(b);
//outputStream.write(b);
//边读边写
int len = 0;
while((len = inputStream.read(b)) != -1){
outputStream.write(len);
}
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 使用java.nio.Channels中的方法
public static void copyByFileChannels(File source, File dest) {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = new FileInputStream(source);
outputStream = new FileOutputStream(dest);
FileChannel inputChannel = inputStream.getChannel();
FileChannel outputChannel = outputStream.getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 使用Java7中Files.copy完成拷贝
/**
* 使用java7的Files.copy完成拷贝操作,其内部也是使用FileChannels
* @param source
* @param dest
*/
public static void copyByJava7Files(File source, File dest) {
try {
Files.copy(source.toPath(),dest.toPath());
} catch (IOException e) {
e.printStackTrace();
}
}
平时最常用的应该就是第一种方式了,但是好像使用FileChannel效率更高,这个还没做性能比较,因为没来得及看源码,日后用到了再说吧。^_^