NIO API java.nio (Java Platform SE 8 )
直接上代码
package com.phil.aoplog.util;
import lombok.extern.slf4j.Slf4j;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
@Slf4j
public class MergeUtils {
public static void main(String[] args) {
String[] filesToMerge = {"合并1.tmp", "合并2.tmp"};
String mergedFileName = "合并.txt";
mergeFiles(filesToMerge, mergedFileName);
}
public static void mergeFiles(String[] filesToMerge, String mergedFileName) {
try (FileChannel outChannel = new FileOutputStream(mergedFileName).getChannel()) {
for (String file : filesToMerge) {
try (FileChannel inChannel = new FileInputStream(file).getChannel()) {
inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IOException e) {
log.error("处理文件读取异常");
}
}
} catch (IOException e) {
log.error("处理文件写入异常");
}
}
}
两个需要合并的文件
合并之后的