Java File
Java File
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 thing we will do is create two objects of type File, which represent the source file and destination file:
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:
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;
try {
InputStream in = new FileInputStream(origen);
OutputStream out = new
FileOutputStream(destino);
in.close();
out.close();
} catch (IOException ioe){
ioe.printStackTrace();
}