Java transfer content from one file to another

Why transfer content from one file to another?

When we do analysis on content in files, we may need to read content from one file and do various kinds of processing (e.g. exclude/add/modify some parts), and then output results to another file. This process occurs very often if you do simple program analysis or file content analysis.

This is the java code quick reference. It simply read the input file line by line, and then output each line to the other file. You can simply copy the code and use it in your project.

public class Main {
	public static void main(String[] args) throws IOException {
		File dir = new File(".");
		String source = dir.getCanonicalPath() + File.separator + "Code.txt";
		String dest = dir.getCanonicalPath() + File.separator + "Dest.txt";
		File fin = new File(source);
		FileInputStream fis = new FileInputStream(fin);
		BufferedReader in = new BufferedReader(new InputStreamReader(fis));
		FileWriter fstream = new FileWriter(dest, true);
		BufferedWriter out = new BufferedWriter(fstream);
		String aLine = null;
		while ((aLine = in.readLine()) != null) {
			//Process each line and add output to Dest.txt file
		// do not forget to close the buffer reader
		// close buffer writer

Note: Do not forget to close the input/output stream to prevent memory problems.

Result Screenshot

Category >> I/O  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. Guest on 2013-12-14


  2. Willem Meijer on 2016-8-25

    Thanks for the nice example!

  3. Matthew Arrivel on 2017-11-1

    Thanks a lot

Leave a comment