Java NIO通道之间的数据传输

在Java NIO中,可以非常频繁地将数据从一个通道传输到另一个通道。批量传输文件数据是非常普遍的,因为几个优化方法已经添加到FileChannel类中,使其更有效率。

通道之间的数据传输在FileChannel类中的两种方法是:

  • FileChannel.transferTo()方法
  • FileChannel.transferFrom()方法

FileChannel.transferTo()方法

transferTo()方法用来从FileChannel到其他通道的数据传输。

下面来看一下transferTo()方法的例子:

public abstract class Channel extends AbstractChannel  
{    
   public abstract long transferTo (long position, long count, WritableByteChannel target);  
}

Java

FileChannel.transferFrom()方法

transferFrom()方法允许从源通道到FileChannel的数据传输。

下面来看看transferFrom()方法的例子:

public abstract class Channel extends AbstractChannel  
{    
    public abstract long transferFrom (ReadableByteChannel src, long position, long count);  
}

Java

基本通道到通道数据传输示例

下面来看看从4个不同文件读取文件内容的简单示例,并将它们的组合输出写入第五个文件:

package com.yiibai;

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

public class TransferDemo {
    public static void main(String[] argv) throws Exception {
        String relativelyPath = System.getProperty("user.dir");
        // Path of Input files
        String[] iF = new String[] { relativelyPath + "/input1.txt", relativelyPath + "/input2.txt",
                relativelyPath + "/input3.txt", relativelyPath + "/input4.txt" };
        // Path of Output file and contents will be written in this file
        String oF = relativelyPath + "/combine_output.txt";
        // Acquired the channel for output file
        FileOutputStream output = new FileOutputStream(new File(oF));
        WritableByteChannel targetChannel = output.getChannel();
        for (int j = 0; j < iF.length; j++) {
            // Get the channel for input files
            FileInputStream input = new FileInputStream(iF[j]);
            FileChannel inputChannel = input.getChannel();

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

            // close an input channel
            inputChannel.close();
            input.close();
        }
        // close the target channel
        targetChannel.close();
        output.close();
        System.out.println("All jobs done...");
    }
}

Java

在上述程序中,将4个不同的文件(即input1.txtinput2.txtinput3.txtinput4.txt)的内容读取并将其组合的输出写入第五个文件,即:combine_output.txt文件的中。combine_output.txt文件的内容如下 -

this is content from input1.txt
this is content from input2.txt
this is content from input3.txt
this is content from input4.txt

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智慧浩海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值