Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Nio: FileChannel: Read and write together


Below step-by-step procedure explains how to copy a file using nio Filechannel.

Step 1: Create FileChannel from source file.
FileInputStream fin = new FileInputStream(sourceFilePath);
FileChannel fileInputChannel = fin.getChannel();

Step 2: Get the FileChannel from FileOutputStream.
FileOutputStream fout = new FileOutputStream(destinationFilePath)
FileChannel fileOutputChannel = fout.getChannel();

Step 3: Read data from fileInputChannel into the buffer and put the buffer in fileOutputChannel.
ByteBuffer buffer = ByteBuffer.allocate(1024);

int noOfBytesRead;

while ((noOfBytesRead = fileInputChannel.read(buffer)) != -1) {
         buffer.flip();
         fileOutputChannel.write(buffer);
         buffer.clear();
}

Find the below working application.

package com.sample.app;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Test {

private static final String SOURCE_FILE_PATH = "C:\\Users\\krishna\\Documents\\Study\\HelloWorld.txt";
private static final String DESTINATION_FILE_PATH = "C:\\Users\\krishna\\Documents\\Study\\HelloWorld(copy).txt";

/**
* Copy contents of the file sourceFilePath to
* destinationFilePath
*
* @param sourceFilePath
* @param destinationFilePath
* @throws IOException
* @throws FileNotFoundException
*/
public static void copyFile(String sourceFilePath, String destinationFilePath)
throws FileNotFoundException, IOException {

if (sourceFilePath == null || sourceFilePath.isEmpty()) {
throw new IllegalArgumentException("sourceFilePath shoudn't be null or empty");
}

if (destinationFilePath == null || destinationFilePath.isEmpty()) {
throw new IllegalArgumentException("destinationFilePath shoudn't be null or empty");
}

try (FileInputStream fin = new FileInputStream(sourceFilePath);
FileOutputStream fout = new FileOutputStream(destinationFilePath)) {
FileChannel fileInputChannel = fin.getChannel();
FileChannel fileOutputChannel = fout.getChannel();

ByteBuffer buffer = ByteBuffer.allocate(1024);

int noOfBytesRead;

while ((noOfBytesRead = fileInputChannel.read(buffer)) != -1) {
buffer.flip();
fileOutputChannel.write(buffer);
buffer.clear();
}

}
}

public static void main(String... args) throws IOException {
copyFile(SOURCE_FILE_PATH, DESTINATION_FILE_PATH);
}
}




Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Nio: FileChannel: Read and write together

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×