Java NIO(三):FileChannel、SocketCh

2018-03-07  本文已影响66人  聪明的奇瑞

FileChannel

RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = inChannel.read(buf);
String str = "abc";
ByteBuffer byteBuffer = ByteBuffer.allocate(48);
byteBuffer.put(str.getBytes());
byteBuffer.flip();
while (byteBuffer.hasRemaining()) {
    fileChannel.write(byteBuffer);
}
channel.close();
long pos = channel.position();
channel.position(pos +123);
long fileSize = channel.size();
channel.truncate(1024);
channel.force(true);

通道间的数据传输

try (RandomAccessFile raf = new RandomAccessFile("/Users/linyuan/Documents/字目录.txt", "rw");
    RandomAccessFile toFile = new RandomAccessFile("/Users/linyuan/Documents/toFile.txt", "rw")) {
    FileChannel fromChannel = raf.getChannel();
    FileChannel toChannel = toFile.getChannel();
    long position = 0;
    long count = fromChannel.size();
    // position 表示从 position 处开始向目标文件写入数据,count 表示最多传输的字节数
    // 如果源通道的剩余空间小于 count 个字节,则所传输的字节数要小于请求的字节数
    toChannel.transferFrom(fromChannel, position, count);
} catch (Exception e) {
    e.printStackTrace();
}

SocketChannel

socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("127.0.0.1", 80));

非阻塞模式

socketChannel.configureBlocking(false);     // 设置为非阻塞模式
socketChannel.connect(new InetSocketAddress("http://www.baidu.com", 80));
while(!socketChannel.finishConnect() ){
    //wait, or do something else...
}

ServerSocketChannel

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(9999));
while(true){
    SocketChannel socketChannel =serverSocketChannel.accept();
    //do something with socketChannel...
}

非阻塞模式

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(9999));
serverSocketChannel.configureBlocking(false);   // 设置为非阻塞模式
while(true){
    SocketChannel socketChannel = serverSocketChannel.accept();
    if(socketChannel != null){
    //do something with socketChannel...
    }
}

DatagramChannel

DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(9999));
ByteBuffer buf = ByteBuffer.allocate(48);
channel.receive(buf);
String str = "新的一天";
ByteBuffer buf = ByteBuffer.allocate(48);
buf.put(str.getBytes());
buf.flip();
channel.send(buf, new InetSocketAddress("localhost", 9999));

连接到特定的地址

channel.connect(new InetSocketAddress("localhost", 80));
int bytesRead = channel.read(buf);
int bytesWritten = channel.write(but);
上一篇 下一篇

猜你喜欢

热点阅读