We can use the FileInputStream and FileOutputStream classes in Java to copy files from one location to another. For this, we must import some specific classes of the java.io package. So, for example, let us use the statement import java.io.*; to include the entire package; The main logic of copying a file is to read the file associated with the FileInputStream variable and write the read content to the file associated with the FileOutputStream variable.
Methods used in the program
/* Program to copy a src file to destination. The name of src file and dest file must be provided using command line arguments where args[0] is the name of source file and args[1] is name of destination file */ import java.io.*; class src2dest { public static void main(String args[]) throws FileNotFoundException,IOException { /* If file doesnot exist FileInputStream throws FileNotFoundException and read() write() throws IOException if I/O error occurs */ FileInputStream fis = new FileInputStream(args[0]); /* assuming that the file exists and need not to be checked */ FileOutputStream fos = new FileOutputStream(args[1]); int b; while ((b=fis.read()) != -1) fos.write(b); /* read() will readonly next int so we used while loop here in order to read upto end of file and keep writing the read int into dest file */ fis.close(); fos.close(); } }
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.