周末无聊。学习了一下nio,就拿他写了个读写文件的,和老的比了一下,速度真的快了很多,后来又用FastCopy 这个小工具比了一下,发现速度差不多,FastCopy 比直接右键复制 黏贴要快很多。下面是代码:
package com.lucene.file;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class FileCopy {
public static String src = "f:\\永远强大.rmvb";
public static String dist = "f:\\永远强大2.rmvb";
/**
* @param args
*/
public static void main(String[] args) {
long start = System.currentTimeMillis();
copyOld();
long end = System.currentTimeMillis();
System.out.println("nio 用时: " + (end - start));
long start2 = System.currentTimeMillis();
copyOld();
end = System.currentTimeMillis();
System.out.println("io 用时: " + (end - start2));
}
public static void copyOld() {
File srcFile = new File(src);
File distFile = new File(dist);
if (distFile.exists()) {
distFile.delete();
}
try {
FileInputStream fin = new FileInputStream(srcFile);
BufferedInputStream buffIn = new BufferedInputStream(fin);
FileOutputStream fout = new FileOutputStream(distFile);
BufferedOutputStream buffout = new BufferedOutputStream(fout);
byte[] bytes = new byte[1024];
while (buffIn.read(bytes) > 0) {
buffout.write(bytes);
}
fin.close();
buffIn.close();
fout.close();
buffout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void copyNew() {
try {
File srcFile = new File(src);
File distFile = new File(dist);
if (distFile.exists()) {
distFile.delete();
}
FileInputStream fin = new FileInputStream(srcFile);
FileOutputStream fout = new FileOutputStream(distFile);
FileChannel inChannel = fin.getChannel();
FileChannel outChannel = fout.getChannel();
int ByteBufferSize = 1024 * 100;
ByteBuffer buff = ByteBuffer.allocate(ByteBufferSize);
while (inChannel.read(buff) > 0) {
buff.flip();
if (inChannel.position() == inChannel.size()) {// 判断是不是最后一段数据
int lastRead = (int) (inChannel.size() % ByteBufferSize);
byte[] bytes = new byte[lastRead];
buff.get(bytes, 0, lastRead);
outChannel.write(ByteBuffer.wrap(bytes));
buff.clear();
} else {
outChannel.write(buff);
buff.clear();
}
}// 这个使用FileChannel 自带的复制
// outChannel.transferFrom(inChannel, 0, inChannel.size());
outChannel.close();
inChannel.close();
fin.close();
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}