© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
Quick Links
Easy Studies

Copy the content from one file to another Using Java


This program is to copy the contents of one file into another. While running the program the file name with the path is given as input. FileInputStream.read () method is used to read the content of the first file. FileOutputStream.write (buffer, 0, length) method writes the content into the second file. FileOutputStream class provides the method to perform the writing operations in the file. FileInputStream class provides the method for getting the information from the file. The given file must be the .txt file. If the destination file is not empty, we can use the append method to append the content into the file. Otherwise the content of the destination file will be replaced. For copying the file byte array is created and the contents of source file are stored temporarily and then written into the destination file.

Copy the content from one file to another Using Java:

import java.io.*; public class CopyFile{ private static void copyfile(String srFile, String dtFile){ try{ File f1 = new File(srFile); File f2 = new File(dtFile); InputStream in = new FileInputStream(f1); //For Append the file. // OutputStream out = new FileOutputStream(f2,true); //For Overwrite the file. OutputStream out = new FileOutputStream(f2); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0){ out.write(buf, 0, len); } in.close(); out.close(); System.out.println("File copied."); } catch(FileNotFoundException ex){ System.out.println(ex.getMessage() + " in the specified directory."); System.exit(0); } catch(IOException e){ System.out.println(e.getMessage()); } } public static void main(String[] args){ switch(args.length){ case 0: System.out.println("File has not mentioned."); System.exit(0); case 1: System.out.println("Destination file has not mentioned."); System.exit(0); case 2: copyfile(args[0],args[1]); System.exit(0); default : System.out.println("Multiple files are not allow."); System.exit(0); } } }

Sample ScreenShot:

SLogix Student Projects

⇓Student Projects⇓
⇑Student Projects⇑