Copying a file from source to destination in Java

Copying a file is very commonly used in Java programs, though there are no API present to copy/paste a file or directory. But there are different ways by which we can copy and paste a java.io.File in Java.

  • We can use FileInputStream and FileOutputStream object to read and write through buffer as below.
//below code throws IOException
InputStream ipStream = new FileInputStream(SOURCE_LOCATION);
OutputStream opStream = new FileOutputStream(DESTINATION_LOCATION); 
byte[] byteBuffer = new byte[1024]; 
int totalLength = 0; 
while ((totalLength = ipStream.read(byteBuffer)) > 0) { 
opStream.write(byteBuffer, 0, totalLength); 
}
  • There is another alternative way of copying a file, In Java1.4 NIO classes were introduced and FileChannel can be used to copy a file in Java. Which was faster than the conventional methid of using Java Streams.
  • There is another way of copying a file/directory from one location to another location using Apache’s jar org.apache.commons.io.jar. Below is the code for same:
package com.debo.replacefile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.io.FileUtils;

public class ReplaceFile {
    public static void main(String[] args) {
        Properties prop = loadProperties();
        String srcDirStr = prop.getProperty(“FILELOCATION.src”);
        String destDirStr = prop.getProperty(“FILELOCATION.dest”);
        moveTheFile(srcDirStr, destDirStr);
    }
    private static Properties loadProperties() {
        Properties prop = new Properties();
        try {
            InputStream ip = new FileInputStream(“file.properties”);
            prop.load(ip);
            ip.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return prop;
    }
    private static void moveTheFile(String srcDirStr, String destDirStr) {
        File srcDir = new File(srcDirStr);
        File destDir = new File(destDirStr);
        try {
            if(!destDir.exists()){
                destDir.mkdir();
            }
            FileUtils.copyDirectory(srcDir, destDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Values in file.properties:

FILELOCATION.src=C:/Users/user/Imp/SomeOtherVal/Example
FILELOCATION.dest=C:/Users/user/Desktop/Softwares/dest

Digiprove sealCopyright secured by Digiprove © 2019 Geeks 18

Be the first to comment

Leave a Reply

Your email address will not be published.


*