Channel
通道
双向:
以文件流为例:
根据输入(fileInputStream)/输出流(fileOutputStram).getChanel的通道不具备双向的特性,
可以使用RandomAccessFile具备双向的特性,即支持读也支持写
import lombok.SneakyThrows;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.StandardCharsets;
public class TestChannel {
@SneakyThrows
public static void main(String[] args) {
byte[] bytes = new byte[10];
InputStream in = System.in;
while (true) {
int len;
while ((len = in.read(bytes)) != -1) {
System.out.println(new String(bytes, 0, len));
}
}
}
static class R {
@SneakyThrows
public static void main(String[] args) {
ByteBuffer allocate = ByteBuffer.allocate(10);
ReadableByteChannel readableByteChannel = Channels.newChannel(System.in);
while (true) {
readableByteChannel.read(allocate);
allocate.flip();
System.out.println(new String(allocate.array(), 0, allocate.remaining()));
allocate.clear();
}
}
}
static class W{
@SneakyThrows
public static void main(String[] args) {
WritableByteChannel writableByteChannel = Channels.newChannel(System.out);
ByteBuffer allocate = ByteBuffer.allocate(10);
String name = "hj";
while (true) {
allocate.put(name.getBytes(StandardCharsets.UTF_8));
allocate.flip();
writableByteChannel.write(allocate);
allocate.clear();
}
}
}
static class RW1{
@SneakyThrows
public static void main(String[] args) {
RandomAccessFile randomAccessFile = new RandomAccessFile("test.txt", "rw");
FileChannel channel = randomAccessFile.getChannel();
byte[] bytes = "伞兵1号卢本伟准备就绪".getBytes(StandardCharsets.UTF_8);
ByteBuffer allocate = ByteBuffer.allocate(bytes.length);
allocate.put(bytes);
allocate.flip();
channel.write(allocate);
System.out.println("写操作完成后文件访问位置"+channel.position());
channel.position(0);
ByteBuffer buf = ByteBuffer.allocate(128);
channel.read(buf);
buf.flip();
System.out.println(new String(buf.array(),0, buf.remaining()));
}
}
}