Copy a file with Java November 11, 2010
Posted by lineadecodigo in: Java , trackback
In this example we see how we can copy a file using Java. So that we end up having a second file with the same content as
the first file.
The first thing we will do is create two objects of type File, which represent the source file and destination file:
File source = new File("origen.txt"),
File destination = new File("destino.txt");
The main idea of the copy will be to open a stream for reading, ie anInputStreamon the source file, do the reading at the
same time we open a stream to write to the destination file, ie a OutputStream. About thisOutputStream will do the deed.
We rely on objects File previously created and in the classes FileInputStreamand FileOutputStream to open the stream in
the files:
InputStream">InputStream">InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(destination);
We read and write while there is data in the stream reading
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
The readings we do with the method . read ().
Now we only have to close the stream by the method . close () to finish the code for our program.
in.close(); out.close();
Note that we need to handle the exception IOException on all code. It is for this reason that we'll have all the code in a try-
catch structure.
package com.lineadecodigo.java.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CopiarFicheros {
public static void main(String[] args) {
File origen = new File("origen.txt");
File destino = new File("destino.txt");
try {
InputStream in = new FileInputStream(origen);
OutputStream out = new
FileOutputStream(destino);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException ioe){
ioe.printStackTrace();
}