Copy the file from the large file

Create the new file from large file, using File Channel and ByteBuffer:

Example : 

import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Date;

public class CopyLargeFileExample {

    public static void main(String args[]) throws IOException {
        long startTime = new Date().getTime();
        // args[0] -- Input source file
        // args[1] -- Destination file
        Path path = Paths.get(URI.create(args[0]));
        Path outFilePath = Paths.get(URI.create(args[1]));

        FileChannel fileChannel = FileChannel.open(path);
        FileChannel outFileChannel = FileChannel.open(outFilePath, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        ByteBuffer buffer = ByteBuffer.allocate(1024 * 250);

        int noOfReadLine = fileChannel.read(buffer);
        while (noOfReadLine != -1) {
            buffer.flip();
            outFileChannel.write(buffer);
            buffer.clear();
            noOfReadLine = fileChannel.read(buffer);
        }

        fileChannel.close();
        outFileChannel.close();
        long endTime = new Date().getTime();

        System.out.println("Complete Time :::" + ((endTime - startTime) / 1000) + " sec");

    }

 

Input file : properties

InputFIle

 

Execution:

D:\share\temp>java CopyLargeFileExample "file:///D:/share/temp/big_file.txt" "file:///D:/share/temp/big_file_copy.txt"
Complete Time :::41 sec

D:\share\temp>

 

Output file :

outfile

Happy coding :)…

 

 

Advertisements


Categories: Java Programming

Tags: ,

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: