File Copying with NIO

Introduction

NIO or New Input Output is part of the java.nio package. This API (Application Programming Interface) has been brought along to support the original framework of I/O streams in Java while enhancing the performance of the same. NIO can be used to efficiently copy files and directories in Java. This article will guide you on how to easily copy files or sub-files using NIO.

The File Copy Methods

To copy files using NIO, the following class needs to be imported: java.nio.files.Files. This class has three methods that can be exploited here:

  • long copy (InputStream in, Path Target, CopyOption …… options) – This method will copy all the bytes from a particular stream into a file. Once done, it will return the number of bytes that have been copied. This should be equal to the Input Stream.
  • long copy (Path source, OutputStream out) – Copies all the bytes of data from a file to an output stream.
  • Path copy (Path source, Path target, CopyOption … options) – Makes a copy of one file onto another and returns the path to the target file.

Example

Let us assume we have a video named “Sample_Program” and it is saved in the C Drive. The complete directory is given in the code. We want to copy the file onto another directory.

Path sourceFile = Paths.get("Sample_Proogram.mp4");
Path targetFile = Paths.get("C:Java\MyFiles\\Sample_Program.mp4");
try
{
Files.copy(sourceFile, targetFile, StandardCopyOption.REPLACE_EXISTING);
}
catch (IOException ex)
{
System.err.format("I/O Error when copying file");
}
//We will save the file on a webpage as an intermediate location.
Path targetFile = Paths.get("Google.html");
URI uri = URI.create("http://google.com");
try (InputStream inputStream = uri.toURL().openStream())
{
Files.copy(inputStream, targetFile);
}
catch (IOException ex)
{
System.err.format("I/O Error when copying file");
}
//Finally, we will copy it into a new directory
import java.io.*;
import java.nio.file.*;
public class CopyFile
{
public static void copyFile(String filePath, String dir)
{
Path sourceFile = Paths.get(filePath);
Path targetDir = Paths.get(dir);
Path targetFile = targetDir.resolve(sourceFile.getFileName());
try {
Files.copy(sourceFile, targetFile);
} catch (FileAlreadyExistsException ex)
{
System.err.format("File %s already exists.", targetFile);
}
catch (IOException ex)
{
System.err.format("I/O Error when copying file");
}
}
public static void main (String[] args)
{
String filePath = args[0];
String dir = args[1];
copyFile(filePath, dir);
}
}

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.