I have a number of .txt
files. I would like to concatenate those and generate a text file.
How would I do it in Java?
file1.txt file2.txt
Concatenation results into
file3.txt
Such that the contents of file1.txt
is followed by file2.txt
.
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).
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);
}
}
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();
this works fine for me.
// open file input stream to the first file file2.txt
InputStream in = new FileInputStream("file1.txt");
byte[] buffer = new byte[1 << 20]; // loads 1 MB of the file
// open file output stream to which files will be concatenated.
OutputStream os = new FileOutputStream(new File("file3.txt"), true);
int count;
// read entire file1.txt and write it to file3.txt
while ((count = in.read(buffer)) != -1) {
os.write(buffer, 0, count);
os.flush();
}
in.close();
// open file input stream to the second file, file2.txt
in = new FileInputStream("file2.txt");
// read entire file2.txt and write it to file3.txt
while ((count = in.read(buffer)) != -1) {
os.write(buffer, 0, count);
os.flush();
}
in.close();
os.close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With