Copy File Example

This program demonstrates copying contents from one file to another.

Problem Statement

Write a Java program that copies contents of one file into another.

Source Code

1 import java.io.*;
2 public class FileCopyExample {
3 public static void main(String[] args) {
4 System.out.println("Eduinq File Copy Example");
5 try(FileInputStream fis=new FileInputStream("sample.txt");
6 FileOutputStream fos=new FileOutputStream("copy.txt")) {
7 int ch;
8 while((ch=fis.read())!=-1){
9 fos.write(ch);
10 }
11 } catch(IOException e) {
12 System.out.println("Eduinq Exception: "+e.getMessage());
13 }
14 }
15 }

Program Output

					Eduinq File Copy Example
(File copy.txt contains same content as sample.txt.)
				

Explanation

File copy uses FileInputStream and FileOutputStream. - Reads byte by byte and writes to destination file. - Exception handling ensures safe file operations. - In enterprise systems, file copy is used for backups. Conclusion: Shows copying file contents.

Quick Links to Explore