用java nio合并两个小文件的方法

摘要: JAVA NIO 的效率比原来的IO API 效率要高,做了一个简单的测试,合并两个小文件,仅仅测试而已。不能直接用于自己的工程中。

JAVA NIO 的效率比原来的IO API 效率要高,做了一个简单的测试,合并两个小文件,仅仅测试而已。不能直接用于自己的工程中。

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个字节。如果要完全合并,可以一个文件一个文件的处理,就可以了。

上一篇: java web开发获取客户端访问ip(透过代理和负载均衡)
下一篇: python解析xml的简单例子
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号