Monday, June 16, 2008

Copy File using Java

FileChannel is class used for reading, writing, mapping, and manipulating a file. File Channels are part of Java New I/O Packages. A file can be viewed as a sequence of bytes. The various Buffer classes in New I/O Packages serve as a container for manipulating the primitive byte contents. It is also possible to allocate a new Buffer object, read and write byte data into the existing Buffer using the Buffer classes. The File Channel objects are tightly associated with the Buffer class, and now File objects are coupled with File Channel object which means that it is now possible to perform read and write data on the files using the File Channel objects.

Sample Java Code

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

public class CopyFile {

public static void main(String[] args) throws Exception{

String file = "input.txt";
FileInputStream source = new FileInputStream(file);
FileOutputStream destination = new FileOutputStream("Output.txt");

FileChannel sourceFileChannel = source.getChannel();
FileChannel destinationFileChannel = destination.getChannel();

long size = sourceFileChannel.size();
sourceFileChannel.transferTo(0, size, destinationFileChannel);
}
}

No comments:

ORM Framework for Kotlin

In Kotlin, ORM (Object-Relational Mapping) libraries provide a convenient way to interact with databases using object-oriented programming p...