Description:
In this section we include a sample source code to demonstrate on how to copy a file in java. This is without calling any external command on the OS level. The solution presented is written in pure java.
Copy file from one folder to another using java.io package
Using java.io library copying file is an easy using FileInputStream and Fileoutputstream. As we all know a File class is an abstract representation of file and path names. We would be needing two objects of File class, one is a source file and the other one is the target file. The FileInputStream class provide mechanism for reading raw bytes of data. On the other hand the FileOutputStream class is meant for writing raw data. This source code shows also basic error trapping FileNotFoundException and IOException.
package com.javatutorialhq.tutorial; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class FileCopyStream { /** * This sample source code shows how to copy a file in java * using java.io package * Property of javatutorialhq.com * All Rights Reserved * Version 1.0 06/11/2012 */ final static String fileInput = "C:\\temp\\testFolder\\netbeans.rar"; final static String fileOutput = "C:\\temp\\testFolder\\Outputfile.rar"; public static void main(String[] args) { try { //source file declaration FileInputStream inputStream = new FileInputStream(new File(fileInput)); //target file declaration FileOutputStream outputStream = new FileOutputStream(new File(fileOutput)); int lengthStream; byte[] buff = new byte[1024]; while((lengthStream=inputStream.read(buff))>0){ //writing to the target file contents of the source file outputStream.write(buff,0,lengthStream); } System.out.println("Done Copying: "+fileOutput); outputStream.close(); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
If you have any insights or questions on the above example, feel free to comment below.