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

akash
         Add "fw.write("\n");" Below "fw.write(s);" for breaking lines on the copied file
manoj
         made the programming so easy.
abhimanyu
         showing error in line 19 Syntax error tell me something
Shreya Hedaoo
         Nice
Sourav Das
         Done g8 job buddy ✌️

©candidjava.com