JavaHow to Use FileChannel in Java

How to Use FileChannel in Java

There are several methods a programmer can use to read to files or write files to a specific destination, such as a folder or directory in a system. One of those ways is by using FileChannel and the java.nio.channels library, as shown in the following quick snippet, courtesy of today’s quick tip Java programming tutorial:

import java.io.*;
import java.nio.channels.*;

public class UnderstandingFileChannels {
	
	String sourceFileName = "UnderstandingFileChannels.java";
	String destFileName = "CopyOfUnderstandingFileChannels.java";
	
	public static void main(String[] args) 
	{  
		UnderstandingFileChannels understandingFileChannels = new UnderstandingFileChannels();
		understandingFileChannels.proceed();
	}

	private void proceed()  
	{
		try 
		{
			copyFileUsingFileChannel(new File(sourceFileName),new File(destFileName));
		}catch(IOException ioe)
		{
			System.out.println("IOException: " + ioe);
		}
	}
	
	private void copyFileUsingFileChannel(File source, File dest) throws IOException {
		FileChannel sourceChannel = null;
		FileChannel destChannel = null;
		try 
		{
			sourceChannel = new FileInputStream(source).getChannel();
			destChannel = new FileOutputStream(dest).getChannel();
			destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
			System.out.println("Copied file " + sourceFileName + " to " + destFileName );
		}
		finally
		{
			sourceChannel.close();
			destChannel.close();
		}
	}
	
}

If you run this code in your integrated development environment (IDE) or code editor, you will get the following output:

[root@mypc]# java UnderstandingFileChannels
Copied file UnderstandingFileChannels.java to CopyOfUnderstandingFileChannels.java
Get the Free Newsletter!
Subscribe to Developer Insider for top news, trends & analysis
This email address is invalid.
Get the Free Newsletter!
Subscribe to Developer Insider for top news, trends & analysis
This email address is invalid.

Latest Posts

Related Stories