Program to demonstrate how to Copy a file from one location to another in Java.
package com.hubberspot.code;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class CopyFile {
public static void main(String[] args) {
// Create a Scanner object which takes System.in object
// this makes us read values from the console
Scanner scanner = new Scanner(System.in);
// In order to copy a file from one location
// to another
// We will prompt user to enter path of file
// in current location and path
// of the location where it wants to copy the file
// Prompting user to enter path of current location
// of file
System.out.println("Enter the path of current location of file : ");
// Scanner objects nextLine() reads output from the console
// entered by user and stores into the string variable
String currentPath = scanner.nextLine().trim();
// Prompting user to enter path of target location of file
System.out.println("Enter the path of target location of file : ");
String targetLocation = scanner.nextLine().trim();
System.out.println();
// Creating a new file object by passing current file name and
// target file name along with the location
File currentFile = new File(currentPath);
File targetFile = new File(targetLocation);
// Creating FileOutputStream and FileInputStream variables
FileOutputStream fileOutputStream = null;
FileInputStream fileInputStream = null;
try {
// Wrapping the File objects created above within
// FileOutputStream and FileInputStream objects
fileOutputStream = new FileOutputStream(currentFile);
fileInputStream = new FileInputStream(targetFile);
// Creating a buffer of byte for storing contents of file
byte[] buffer = new byte[4096];
int read;
// looping the file contents on the current location till
// it becomes empty
while ((read = fileInputStream.read(buffer)) != -1) {
// As each loops terminates the target file gets the
// contents of current file in the chunks of buffer
fileOutputStream.write(buffer, 0, read);
}
// catch blocks for closing of the streams and catching
// IOException
} catch(IOException e) {
try {
e.printStackTrace();
if (fileInputStream != null) {
fileInputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
}
catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
Output of the program :
