Copy of a File TutorialFrom WikiJavabuy this book File Copy is a standard I/O example, this tutorial explains the steps of how to build a simple progam to copy the content of a file into another. the program is used as follows: java FileCopy <sourceFile> <destinationFile> it copies the content of <sourceFile> into the new file called <destinationFile>
the articleThe first thing this little program does is to verify that there were passed in the command line two operands. the java.io.FileInputStream and java.io.FileOutputStream respectively for reading data from a file and from writing to another one: FileInputStream fileInputStream = new FileInputStream(new File(input)); FileOutputStream fileOutputStream = new FileOutputStream(new File(output));
while (fileInputStream.available() != 0) { if the value is greater than zero, it reads the content of the file and writes the content to the output file: fileOutputStream.write(fileInputStream.read()); when there's no more data to read in the input file the loop ends and the two streams are closed. fileInputStream.close(); fileOutputStream.close();
the complete code
package org.wikijava.copyfiles; import java.io.*; /** * copies a file into another * * @author Giulio */ public class FileCopy { /** * * @param args * @throws IOException * if one or both the files where not accessible */ public static void main(String[] args) throws IOException { if (args.length < 2) { System.out.println("Usage: \n FileCopy sourceFile destinationFile"); return; } String input = args[0]; String output = args[1]; // opens an input stream FileInputStream fileInputStream = new FileInputStream(new File(input)); // open an output stream FileOutputStream fileOutputStream = new FileOutputStream(new File( output)); // While there are characters available in the input file while (fileInputStream.available() != 0) { // read them from the input file and write them in the output file fileOutputStream.write(fileInputStream.read()); } // close the streams fileInputStream.close(); fileOutputStream.close(); } } |
