网上的文件操作目前都停留在老的IO API当中,这大概就是为什么NIO(New IO)都已经不new了,在中国吃透的人还是很少的缘故吧?
不要用循环了,来用NIO吧,只要你的JDK在1.5以上,Follow Me!
我们用到的是FileChannel中的2个方法
transferFrom(ReadableByteChannel src, long position, long count)
transferTo( long position, long count, WritableByteChannel dest)
这2个方法,其实都一样,就是源和目标换一下而已
package com.eric.thinking.java.nio;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
public class TansformExample {
public static void main(String[] args) throws IOException {
RandomAccessFile fromFile = new RandomAccessFile("data/nio-data.txt",
"rw");
FileChannel fromChannel = fromFile.getChannel();
RandomAccessFile toFile = new RandomAccessFile("data/nio-to.txt", "rw");
FileChannel toChannel = toFile.getChannel();
long position = 0;
long count = fromChannel.size();
toChannel.transferFrom(fromChannel, position, count);
fromFile.close();
toFile.close();
}
}
简单吧?