java nio

Java NIO 

RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
FileChannel      fromChannel = fromFile.getChannel();

RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
FileChannel      toChannel = toFile.getChannel();

long position = 0;
long count    = fromChannel.size();

toChannel.transferFrom(fromChannel, position, count);


Additionally, some SocketChannel implementations may transfer only the data theSocketChannel has ready in its internal buffer here and now - even if theSocketChannel may later have more data available. Thus, it may not transfer the entire data requested (count) from theSocketChannel into FileChannel.

-----SocketChannel 实现只传输那些此时已经在内部buffer中准备好的数据,即使过一会有可用的数据也不会被传输。因此这个方法不能把所有的数据从SocketChannel 传递FileChannerl.SocketChannel 实现只传输那些此时已经在内部buffer中准备好的数据,即使过一会有可用的数据也不会被传输。因此这个方法不能把所有的数据从SocketChannel 传递FileChannerl.

RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
FileChannel      fromChannel = fromFile.getChannel();

RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
FileChannel      toChannel = toFile.getChannel();

long position = 0;
long count    = fromChannel.size();

fromChannel.transferTo(position, count, toChannel);

The SocketChannel implementation may only transfer bytes from the FileChannel until the send buffer is full, and then stop.

------直到发送buffer满了,SocketChannel 就从FileChannel中传输字节,然后就停止。


Selector selector = Selector.open();

channel.configureBlocking(false);

SelectionKey key = channel.register(selector, SelectionKey.OP_READ);//这个类里很多方法,可以获得chanel等等,这个key是注册的所有key,后面还有响应单个事件的key


while(true) {///设置了非阻塞的所以,有个死循环。

  int readyChannels = selector.select();

  if(readyChannels == 0) continue;


  Set<SelectionKey> selectedKeys = selector.selectedKeys();

  Iterator<SelectionKey> keyIterator = selectedKeys.iterator();

  while(keyIterator.hasNext()) {

    SelectionKey key = keyIterator.next();

    if(key.isAcceptable()) {
        // a connection was accepted by a ServerSocketChannel.

    } else if (key.isConnectable()) {
        // a connection was established with a remote server.

    } else if (key.isReadable()) {
        // a channel is ready for reading

    } else if (key.isWritable()) {
        // a channel is ready for writing
    }

    keyIterator.remove();///需要自己清楚,当有对应事件时,会被重新添加进来
  }
}



A FileChannel cannot be set into non-blocking mode. It always runs in blocking mode.

------FileChannel不能设置为非阻塞模式,它只工作在阻塞模式

Opening a FileChannel (打开)

RandomAccessFile aFile     = new RandomAccessFile("data/nio-data.txt", "rw");
FileChannel      inChannel = aFile.getChannel();


Reading Data from a FileChannel(FileChannel读取数据)

ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = inChannel.read(buf);

 If -1 is returned, the end-of-file is reached.   ---如果返回-1,到达文件结束

Writing Data to a FileChannel (FileChannel写数据)

String newData = "New String to write to file..." + System.currentTimeMillis();

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());

buf.flip();

while(buf.hasRemaining()) {
    channel.write(buf);
}

Closing a FileChannel (关闭 FileChannel)

channel.close();   


FileChannel Position(FileChannel的位置获取和设置)

long pos= channel.position();//获取

channel.position(pos +123);//设置
If you set the position after the end of the file, and try to read from the channel, you will get -1 - the end-of-file marker. If you set the position after the end of the file, and write to the channel, the file will be expanded to fit the position and written data. This may result in a "file hole", where the physical file on the disk has gaps in the written data.

----------如果设置的位置超过文件大小,并且在读取的时候会立即返回-1标志位。当写的时候,文件就会被扩大,然后写入数据。这就会出现“file hole” ,硬盘上的物理文件写数据时会有间隔。


FileChannel Size(FileChannel大小)

long fileSize = channel.size();


channel.truncate(1024);

This example truncates the file at 1024 bytes in length. ---在特定大小长度截断


The FileChannel.force() method flushes all unwritten data from the channel to the disk. An operating system may cache data in memory for performance reasons, so you are not guaranteed that data written to the channel is actually written to disk, until you call the force() method.


Opening a SocketChannel

SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("http://jenkov.com", 80));
Closing a SocketChannel

socketChannel.close();   


Reading from a SocketChannel

ByteBuffer buf = ByteBuffer.allocate(48);

String newData = "New String to write to file..." + System.currentTimeMillis();

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());

buf.flip();

while(buf.hasRemaining()) {
    channel.write(buf);
}


Non-blocking Mode

You can set a SocketChannel into non-blocking mode. When you do so, you can call connect(), read() and write() in asynchronous mode.


connect()

If the SocketChannel is in non-blocking mode, and you call connect(), the method may return before a connection is established. To determine whether the connection is established, you can call the finishConnect() method, like this:

socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("http://jenkov.com", 80));

while(! socketChannel.finishConnect() ){
    //wait, or do something else...    
}

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

serverSocketChannel.socket().bind(new InetSocketAddress(9999));

while(true){
    SocketChannel socketChannel = serverSocketChannel.accept();

    //do something with socketChannel...
}


Non-blocking Mode


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... }
}



int bytesRead = socketChannel.read(buf);


Opening a DatagramChannel

DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(9999));
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();

channel.receive(buf);


String newData = "New String to write to file..."
                    + System.currentTimeMillis();
   
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();

int bytesSent = channel.send(buf, new InetSocketAddress("jenkov.com", 80));


It is possible to "connect" a DatagramChannel to a specific address on the network. Since UDP is connection-less, this way of connecting to an address does not create a real connection, like with a TCP channel. Rather, it locks your DatagramChannel so you can only send and receive data packets from one specific address.

Here is an example:

channel.connect(new InetSocketAddress("jenkov.com", 80));    






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值