java如何合并文件
合并文件的方法
在Java中合并文件可以通过多种方式实现,以下是几种常见的方法:
使用FileInputStream和FileOutputStream
通过逐个读取源文件内容并写入目标文件实现合并。
import java.io.*;
public class FileMerger {
public static void mergeFiles(String[] sourceFiles, String targetFile) throws IOException {
try (FileOutputStream fos = new FileOutputStream(targetFile)) {
for (String sourceFile : sourceFiles) {
try (FileInputStream fis = new FileInputStream(sourceFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
}
}
}
}
}
使用Files类和Path接口(Java 7+)
利用Java NIO的Files类简化文件操作。
import java.nio.file.*;
import java.io.IOException;
public class FileMergerNIO {
public static void mergeFiles(String[] sourceFiles, String targetFile) throws IOException {
Path targetPath = Paths.get(targetFile);
try (OutputStream out = Files.newOutputStream(targetPath, StandardOpenOption.CREATE)) {
for (String sourceFile : sourceFiles) {
Files.copy(Paths.get(sourceFile), out);
}
}
}
}
使用SequenceInputStream
SequenceInputStream可以将多个输入流串联起来,实现文件合并。

import java.io.*;
import java.util.*;
public class FileMergerSequence {
public static void mergeFiles(String[] sourceFiles, String targetFile) throws IOException {
Vector<InputStream> streams = new Vector<>();
for (String sourceFile : sourceFiles) {
streams.add(new FileInputStream(sourceFile));
}
try (SequenceInputStream sis = new SequenceInputStream(streams.elements());
FileOutputStream fos = new FileOutputStream(targetFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = sis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
}
}
}
注意事项
- 处理大文件时建议使用缓冲区,避免内存溢出。
- 合并二进制文件(如图片、视频)时需确保使用字节流而非字符流。
- 操作完成后及时关闭所有流资源,推荐使用try-with-resources语句。
以上方法可根据具体需求选择,NIO方式通常性能更好,适合现代Java应用开发。






