Monday, 21st June 2010
The new frontier for learning Java

Copy of a File Tutorial

From WikiJava

Jump to: navigation, search
The author suggests:

buy 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>


Contents

the article

The 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));


It then uses a while loop to check if there is any data to read from the input file:

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

Image:250px-Subversion.png
You can download the complete code of this article from the Subversion repository at this link

Using the username:readonly and password: readonly

See the using the SVN repository instructions page for more help about this.
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();
    }
}

Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Title (required):

Website:

Comment: