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

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));

}

}

另外注意的是,我测试的from1.txt,from2.txt 文件都很小,所以能完整合并,如果都是大文件的话,这个方法只是窃取了前面1024个字节。如果要完全合并,可以一个文件一个文件的处理,就可以了。

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)); } } 另外注意的是,我测试的from1.txt,from2.txt 文件都很小,所以能完整合并,如果都是大文件的话,这个方法只是窃取了前面1024个字节。如果要完全合并,可以一个文件一个文件的处理,就可以了。
经验分享 程序员 微信小程序 职场和发展