Advertisement
|
This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
RE: File Copy
Posted by Kishori Sharan on September 06, 2000 at 11:49 AM
Hi Here is the code in FileCopy.java to copy a file. You can do the second problem reading thru the code of FileCopy.java because it also uses reading from and writing to a file. Thanx Kishori /////////////FileCopy.java import java.io.* ; public class FileCopy { private static void quit ( String str) { System.out.println ( str ) ; System.exit ( 1 ) ; } public static void main ( String[] args ) { // Varibles to hold source and destination files String sourceFileName ; String targetFileName ; // Temporary string object to get input from user String temp = "" ; // Prompt user to specify the source and destination files System.out.println ( "Please specify source and destination files name separated by space(s) "); // Prepare the input stream to read the file names BufferedReader in = new BufferedReader ( new InputStreamReader ( System.in ) ) ; try { temp = in.readLine ( ).trim ( ) ; } catch ( IOException e ) { } // Make sure user entered the file names if ( temp == null || temp.length() == 0 ) { quit ( "Invalid files name" ) ; } /* Get the source and target file names */ // Find the position of space(s) int space = temp.indexOf ( " " ) ; if ( space == -1 ) { quit ( "Invalid file names" ) ; } sourceFileName = temp.substring ( 0, space ) ; targetFileName = temp.substring ( space + 1 ).trim ( ) ; // Check if source file exists File source = new File ( sourceFileName ) ; if ( !source.exists() ) { quit ( sourceFileName + " doesn't exist." ) ; } // Check if source is a file if ( !source.isFile ( ) ) { quit ( sourceFileName + " is not a file." ) ; } // Check if target file exists File target = new File ( targetFileName ) ; if ( target.exists() ) { // Prompt user for overwriting the target file System.out.print ( "\nOverwrite " + targetFileName + " (Y/N)?" ) ; try { temp = in.readLine ( ) ; if ( temp == null ) { quit ( "Unknown problem" ) ; } if ( !temp.toUpperCase().equals( "Y" ) ) { quit ( "" ) ; } } catch ( IOException e ) { quit ( "UnKnown problem" ) ; } } // Prepare the input and output streams for final file copy BufferedWriter out = null ; try { out = new BufferedWriter ( new FileWriter ( target ) ) ; in = new BufferedReader ( new FileReader ( source ) ) ; } catch ( IOException e ) { quit ( "Unknown Problem") ; } try { int ch ; ch = in.read ( ) ; while ( ch != -1 ) { out.write ( ch ) ; ch = in.read ( ) ; } } catch ( IOException e ) { } finally { try { in.close ( ) ; out.close ( ); } catch ( IOException e ) { }
} } }
Replies:
|