4

java | channel 互相传输数据以及传输大文件数据

 1 year ago
source link: https://benpaodewoniu.github.io/2023/01/05/java174/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

channel 互相传输数据以及传输大文件数据。

两个 channel 传输

package com.redisc;

import lombok.extern.slf4j.Slf4j;

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

@Slf4j(topic = "c.Test")
public class Run {

public static void main(String[] args) {
try (FileChannel from = new FileInputStream("src/main/resources/data.txt").getChannel();
FileChannel to = new FileOutputStream("src/main/resources/data2.txt").getChannel();
) {
// 效率高,底层会利用操作系统的零 copy 优化
from.transferTo(0, from.size(), to);
} catch (IOException e) {
}
}

}

大文件传输

上面的 from.transferTo(0, from.size(), to); 最大传输 2G 大小。

如果大于 2G ,需要多次传输。

package com.redisc;

import lombok.extern.slf4j.Slf4j;

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

@Slf4j(topic = "c.Test")
public class Run {

public static void main(String[] args) {
try (FileChannel from = new FileInputStream("src/main/resources/data.txt").getChannel();
FileChannel to = new FileOutputStream("src/main/resources/data2.txt").getChannel();
) {
long size = from.size();
for (long left = size; left > 0; ) {
left -= from.transferTo((size - left), left, to);
}
} catch (IOException e) {
}
}

}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK