用java nio合并两个小文件的方法
By:Roy.LiuLast updated:2013-02-27
	    
	        JAVA NIO 的效率比原来的IO API 效率要高,做了一个简单的测试,合并两个小文件,仅仅测试而已。不能直接用于自己的工程中。
重点关注的就是 ByteBuffer 和 ByteBuffer数组,FileChanel 可以接收一个数组类型的ByteBuffer, 从而实现了合并两个文件。
另外注意的是,我测试的from1.txt,from2.txt 文件都很小,所以能完整合并,如果都是大文件的话,这个方法只是窃取了前面1024个字节。如果要完全合并,可以一个文件一个文件的处理,就可以了。
	    
	    
	    
	
package nio.sample.gather;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class FileGathering {
    public static void main(String[] args) throws IOException {
        long start = System.currentTimeMillis();
        File fileIn1 = new File("C:\\from1.txt");
        File fileIn2 = new File("C:\\from2.txt");
        File fileOut = new File("C:\\to.txt");
        FileInputStream fin1 = new FileInputStream(fileIn1);
        FileInputStream fin2 = new FileInputStream(fileIn2);
        FileOutputStream fout = new FileOutputStream(fileOut);
        FileChannel fcIn1 = fin1.getChannel();
        FileChannel fcIn2 = fin2.getChannel();
        ByteBuffer[] bufferArray = new ByteBuffer[2];
        bufferArray[0] = ByteBuffer.allocate(1024);
        bufferArray[1] = ByteBuffer.allocate(1024);
        fcIn1.read(bufferArray[0]);
        fcIn2.read(bufferArray[1]);
        bufferArray[0].flip();
        bufferArray[1].flip();
        FileChannel fcOut = fout.getChannel();
        fcOut.write(bufferArray);
        long end = System.currentTimeMillis();
        System.out.println("time used" + (end - start));
    }
}
重点关注的就是 ByteBuffer 和 ByteBuffer数组,FileChanel 可以接收一个数组类型的ByteBuffer, 从而实现了合并两个文件。
另外注意的是,我测试的from1.txt,from2.txt 文件都很小,所以能完整合并,如果都是大文件的话,这个方法只是窃取了前面1024个字节。如果要完全合并,可以一个文件一个文件的处理,就可以了。
From:一号门
Previous:java web开发获取客户端访问ip(透过代理和负载均衡)
Next:python解析xml的简单例子

COMMENTS