Concatenating a number of .txt files in Java
Read file-by-file and write them to target file. Something like the following:
OutputStream out = new FileOutputStream(outFile);
byte[] buf = new byte[n];
for (String file : files) {
InputStream in = new FileInputStream(file);
int b = 0;
while ( (b = in.read(buf)) >= 0)
out.write(buf, 0, b);
in.close();
}
out.close();
Using Apache Commons IO
You could use the Apache Commons IO library. This has the FileUtils
class.
// Files to read
File file1 = new File("file1.txt");
File file2 = new File("file2.txt");
// File to write
File file3 = new File("file3.txt");
// Read the file as string
String file1Str = FileUtils.readFileToString(file1);
String file2Str = FileUtils.readFileToString(file2);
// Write the file
FileUtils.write(file3, file1Str);
FileUtils.write(file3, file2Str, true); // true for append
There are also other methods in this class that could help accomplish the task in a more optimal way (eg using streams or lists).
Using Java 7+
If you are using Java 7+
public static void main(String[] args) throws Exception {
// Input files
List<Path> inputs = Arrays.asList(
Paths.get("file1.txt"),
Paths.get("file2.txt")
);
// Output file
Path output = Paths.get("file3.txt");
// Charset for read and write
Charset charset = StandardCharsets.UTF_8;
// Join files (lines)
for (Path path : inputs) {
List<String> lines = Files.readAllLines(path, charset);
Files.write(output, lines, charset, StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
}
}