Q:

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

belongs to collection: Java File Handling Programs

0

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.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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...

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java File Handling Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to read a file line by line... >>
<< Java program to get file creation, last access and...