channel
互相传输数据以及传输大文件数据。
两个 channel 传输
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| 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(); ) { from.transferTo(0, from.size(), to); } catch (IOException e) { } }
}
|
大文件传输
上面的 from.transferTo(0, from.size(), to);
最大传输 2G 大小。
如果大于 2G ,需要多次传输。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| 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) { } }
}
|