Home Tutorial Java Core Files Java Concatenate files

 
 

Share on Google+Share on Google+
Java Concatenate files
Posted on: June 17, 2006 at 12:00 AM
Advertisement
In this section, you will learn how to concatenate files in java.

Java Concatenate files

In this section, you will learn how to concatenate files in java.

Concatenating a file, or a series of files, to a single file is a common task. You can concatenate the file either by using the streams or by manual coding. We have used the latter one.

You can see in the given example, we have listed the files using listFile() from a particular directory. And then using the getPath() method, we have referred all the listed files to the FileReader and BufferedReader which reads the files one by one and store the data into another text file. This destination file is different from all these files and will be created if it does not exist.

Here is the code:

import java.io.*;

public class ConcatenatedFiles {

	static public void main(String arg[]) throws java.io.IOException {
		PrintWriter pw = new PrintWriter(new FileOutputStream("C:/concat.txt"));
		File file = new File("C:/Text/");
		File[] files = file.listFiles();
		for (int i = 0; i < files.length; i++) {

			System.out.println("Processing " + files[i].getPath() + "... ");
			BufferedReader br = new BufferedReader(new FileReader(files[i]
					.getPath()));
			String line = br.readLine();
			while (line != null) {
				pw.println(line);
				line = br.readLine();
			}
			br.close();
		}
		pw.close();
		System.out.println("All files have been concatenated into concat.txt");
	}
}

Through the above code, you can concatenate number of text files.

Advertisement

Related Tags for Java Concatenate files:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 17, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com