In this tutorial, you will learn how to copy the content of one file to another in java. Here the new file is created where the content of another file is copied to this newly created file.
Java Program to Copy Content from one File to another File
First, save the content in a text file with the same name that you enter in a program.
For this example, a text file saved with the name javaCode.txt
javaCode.txt
Welcome to Simple2Code.
Let Start
first tutorial
second Program
And after the execution new file will be created as named copiedJavaCode.txt. And the content will be copied to this text file.
Source Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | //copy content from one to another file import java.io.*; public class CopyFile { public static void main(String[] args) throws IOException { File f1 = new File("javaCode.txt"); //saved file File f2 = new File("copiedJavaCode.txt"); //destined file FileReader fr = new FileReader(f1); //file reader object BufferedReader br=new BufferedReader(fr); //buffer reader object FileWriter fw= new FileWriter(f2); //file writer object String s=null; while((s = br.readLine())!=null) //Copying Content to the new file { fw.write(s); fw.write("\n"); fw.flush(); } fw.close(); System.out.println("Successfully Copied."); System.out.println("Check the copiedJavaCode.txt."); } } |
Output: After execution check your copiedJavaCode.txt file where all the content is copied from javaCode.txt file.
Successfully Copied.
Check the copiedJavaCode.txt.