JAVA文件合并操作效率研究

来源:互联网 发布:网络推广金融好做么 编辑:程序博客网 时间:2024/06/05 07:21

下面代码采用两中方式进行文件的合并操作,结果发现FileChannel方式并不见得能够提高多少效率(可能是我测试代码的问题,先帖出来,再分析下,并请大家指正)。

import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.RandomAccessFile;import java.nio.channels.FileChannel;import java.nio.channels.FileChannel.MapMode;public class Test_001 {public static void main(String[] args) throws Exception {File path = new File("/usr/test/");//init(path, 1024 * 1024 * 5, 250);//merager1(path);  //70821  37209init(path, 1024 * 1024 * 5, 250);merager2(path);  //37752}private static void merager1(File path) throws IOException {File[] temp = path.listFiles();File toFile = path.createTempFile("mearage1_", null, path);long start = System.currentTimeMillis();FileChannel toFileChannel = new RandomAccessFile(toFile, "rw").getChannel();FileChannel fromFileChannel = null;for(File from : temp){fromFileChannel = new FileInputStream(from).getChannel();fromFileChannel.transferTo(0, fromFileChannel.size(), toFileChannel);fromFileChannel.close();}toFileChannel.close();System.out.println(System.currentTimeMillis() - start); //28729  31229  28595 29001 24677}private static void merager2(File path) throws IOException {File[] temp = path.listFiles();File toFile = path.createTempFile("mearage2_", null, path);long start = System.currentTimeMillis();RandomAccessFile toRF = new RandomAccessFile(toFile, "rw");toRF.seek(toFile.length());byte[] buf = new byte[1024 * 4];InputStream in = null;for(File from : temp){in = new FileInputStream(from);int len = 0;while((len = in.read(buf)) != -1){toRF.write(buf, 0 ,len);}in.close();}toRF.close();System.out.println(System.currentTimeMillis() - start);  //32021}private static void init(File path, long fileSize, int num) throws IOException{if(path.exists()){for(File f : path.listFiles()){f.deleteOnExit();}}else{path.mkdirs();}for(int i=0; i<num; i++){createFile(path.createTempFile("test_" + i, null, path), fileSize);}}private static void createFile(File file, long size) throws IOException {file.delete();RandomAccessFile rf = new RandomAccessFile(file, "rw");FileChannel fc = rf.getChannel();fc.map(MapMode.READ_WRITE, 0, size);}}