Copying content from one file to another using java


FileReader and FileWriter can be combined together to copy a content from one file to another

Example

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileCopyExample {

	public static void main(String[] args) {

		try {
			FileReader fr = new FileReader("input.txt");
			BufferedReader br = new BufferedReader(fr);
			FileWriter fw = new FileWriter("output.txt", true);
			String s;

			while ((s = br.readLine()) != null) { // read a line
				fw.write(s); // write to output file
				fw.flush();
			}
			br.close();
			fw.close();
                        System.out.println("file copied");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
Run the above program and check the output




Related Post

Comments

Amit
         But its not creating new line character? eg If file1 have 123 456 output file is like 123456 Can you please tell how to do?
Mathan
         Add fw.write("/n"); after fw.write(s);

©candidjava.com