ADVERTISEMENT
ADVERTISEMENT

Java program to read content from one file and write it into another file

In this java program, we are going to learn how to read content from one file and write it into another file?
Submitted by IncludeHelp, on November 19, 2017

Given a file and we have to read content from it and write in another file using java program. This is an example of File Handling in Java.

Program to read content from a file and write in another in java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class CopyFile {
  public static void main(String[] args) {
    try {
      boolean create = true;
      Scanner KB = new Scanner(System.in);

      System.out.print("Enter Source File Name:");
      String sfilename = KB.next();
      File srcfile = new File(sfilename);
      if (!srcfile.exists()) {
        System.out.println("File Not Found..");
      } else {
        FileInputStream FI = new FileInputStream(sfilename);
        System.out.print("Enter Target File Name:");
        String tfilename = KB.next();
        File tfile = new File(tfilename);
        if (tfile.exists()) {
          System.out.print("File Already Exist OverWrite it..Yes/No?:");
          String confirm = KB.next();
          if (confirm.equalsIgnoreCase("yes")) {
            create = true;
          } else {
            create = false;
          }
        }
        if (create) {
          FileOutputStream FO = new FileOutputStream(tfilename);
          int b;
          //read content and write in another file
          while ((b = FI.read()) != -1) {
            FO.write(b);
          }
          System.out.println("\nFile Copied...");
        }
        FI.close();
      }
    } catch (IOException e) {
      System.out.println(e);
    }
  }
}

Output

File Copied...

Java File Handling Programs »


ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.