[an error occurred while processing this directive]
Domain for sale!
Start Search Contents Index Links About

Java cp

A simple copy utility

2005 - Week 47 - Havard Rast Blok

On of the Remember Java visitors recently requested an example on how to opy files in Java. And more specifically, how to copy a section of one file into a new one. The following classes brings you two very simple solutions, which you could develop further.

The first example is over-simplified; it has no user input error checking, no access checking and will overwrite any existing file. The only thing to note, is the use of the buffered streams for input and output. This enables efficent file operations without having to write extra code. In fact, it boils the actual copy operation down to a single lined while loop.

BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
		
int b;
while( (b = in.read()) != -1) {
  out.write(b);
}
		
in.close();
out.close();


CopyFile.java

The second example adds some user input and file access checks; it will terminate if two file arguments are not supplied, but also if the source argument is not an existing file or it can not be read. Finally, it will stop if the destination file already exisits, which could of course be change to depend on some user argument.


CopyFile.java

The finaly example this week will do what was originally requested; copy only a section of the source file to a new destination file. Two new arguments are thus required: the offset at which to start reading, and the number of bytes (or alternativly lines) to read. We'll make the example as simple as possible; four arguments are required, two for source and destination files, and two for start offset and length of sub-section:

java CopyFilePart <source> <destination> <start> <length>


CopyFilePart.java



site: Håvard Rast Blok
mail:
updated: 16 July 2010