belongs to collection: Java File Handling Programs
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.
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...
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Program to read content from a file and write in another in java
Output