In this tutorial you will learn how to copy file from one location to another location
Copy File from One Location to Another
To Copy a file from one location to another location open a FileInputStream and FileOutputStream reference variable from the source and desination file respecivly.
FileInputStream fileInputStream = new FileInputStream(sourceFile); FileOutputStream fileOutputStream = new FileOutputStream(destinationFile);
Make an Array of byte and read from one stream to a buffer and write to another stream
int bufferSize;
byte[] bufffer = new byte[512];
while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
fileOutputStream.write(bufffer, 0, bufferSize);
}
The Following is a complete code to Copy file from one location to another location
CopyFileExample.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class CopyFileExample {
public static void main(String[] args) {
try {
File sourceFile = new File("D:\\registration.jsp");
File destinationFile = new File("F:\\" + sourceFile.getName());
CopyFileExample copyFileExample = new CopyFileExample();
copyFileExample.copyFile(sourceFile, destinationFile);
} catch (Exception e) {
e.printStackTrace();
}
}
public void copyFile(File sourceFile, File destinationFile) {
try {
FileInputStream fileInputStream = new FileInputStream(sourceFile);
FileOutputStream fileOutputStream = new FileOutputStream(
destinationFile);
int bufferSize;
byte[] bufffer = new byte[512];
while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
fileOutputStream.write(bufffer, 0, bufferSize);
}
fileInputStream.close();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

[ 0 ] Comments