HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java New Input/Output / Java NIO FileChannel transferTo() and transferFrom()

Java NIO FileChannel transferTo() and transferFrom()

As in normal Java applications where IO happens mostly between an input source and output target, in NIO as well we may need to transfer data from one channel to another channel very frequently.

Bulk transfers of file data from one place to another is so common that a couple of optimization methods have been added to the FileChannel class to make it even more efficient.

1. Data Transfer between Channels

Java NIO provides two methods for transferring the data between two channels:

  • FileChannel.transferTo()
  • FileChannel.transferFrom()

The transferTo() and transferFrom() methods allow us to cross-connect one channel to another. This eliminates the need to pass the data through an intermediate buffer.

These methods exist only on the FileChannel class, so one of the channels involved in a channel-to-channel transfer must be a FileChannel.

public abstract class FileChannel
        extends AbstractChannel
        implements ByteChannel, GatheringByteChannel, ScatteringByteChannel
{
        // There are more other methods
        public abstract long transferTo (long position, long count, WritableByteChannel target);
        public abstract long transferFrom (ReadableByteChannel src, long position, long count);
}

We can’t do direct transfers between socket channels, but socket channels implement WritableByteChannel and ReadableByteChannel, so the content of a file can be transferred to a socket with transferTo(), or data can be read from a socket directly into a file with transferFrom().

Also, keep in mind that these methods may throw java.io.IOException if any error is encountered during the transfer.

Channel-to-channel transfers can potentially be extremely fast, especially where the underlying operating system provides native support. Some operating systems can perform direct transfers without ever passing the data through user-space. This can be a huge win for high-volume data transfer.

2. FileChannel transferTo() and transferFrom() Example

In this example, we are reading the file content from 3 different files and writing their combined output into a fourth file.

package com.howtodoinjava.nio;

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

public class ChannelTransferExample 
{
	public static void main(String[] argv) throws Exception 
	{
		//Input files
		String[] inputFiles = new String[]{"inputFile1.txt","inputFile2.txt","inputFile3.txt"};
		
		//Files contents will be written in these files
		String outputFile = "outputFile.txt";
		
		//Get channel for output file
		FileOutputStream fos = new FileOutputStream(new File(outputFile));
		WritableByteChannel targetChannel = fos.getChannel();
		
		for (int i = 0; i < inputFiles.length; i++)
		{
			//Get channel for input files
			FileInputStream fis = new FileInputStream(inputFiles[i]);
			FileChannel inputChannel = fis.getChannel();

			//Transfer data from input channel to output channel
			inputChannel.transferTo(0, inputChannel.size(), targetChannel);

			//close the input channel
			inputChannel.close();
			fis.close();
		}
		
		//finally close the target channel
		targetChannel.close();
		fos.close();
	}
}

Drop your comments and suggestions in the comments section.

Happy Learning !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Abhinav

    January 19, 2015

    Hi Lokesh,

    I am very big fan of your blog and read as much as time permits me. I have a request for you that i have only limited access for internet so i am not read your article as i am offline. So can you please give an option to download as a PDF formate. I have tried to save the web pages but some time it miss the diagram and code snippets than it’s not useful in that case.
    Thanks
    Abhinav

    • Lokesh Gupta

      January 19, 2015

      I will explore this possibility. Thanks for the feedback.

Comments are closed on this article!

Search Tutorials

Java New IO

  • Java NIO Introduction
  • Java NIO Path
  • Java NIO Buffers
  • Java NIO Channels
  • Java NIO Read File
  • Java NIO MappedByteBuffer
  • Java NIO Vectored IO
  • Data Transfer between Channels

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)