Java 7 I/O新功能探秘:同步操作,多播与随机存取

欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入

  ◆SeekableByteChannel:随机访问通道;

  ◆MulticastChannel:允许IP多播的通道;

  ◆NetworkChannel:新的网络通道超级接口;

  ◆异步I/O API:新的API使I/O操作可以异步进行。

  SeekableByteChannel

  首先,Java 7包括新的ByteChannel – SeekableByteChannel,这个通道维护当前的位置,你可以读写该位置,并允许随机访问。使用这个类型的通道,你可以添加多个线程读/写在不同位置相同的线程。

  1.SeekableByteChannel channel1 = Paths.get(“Path to file”).newByteChannel(); //Simply READ

  2.SeekableByteChannel channel2 = Paths.get(“Path to file”).newByteChannel(StandardOpenOption.READ, StandardOpenOption.WRITE); //READ and WRITE

  你可以使用下面这些方法操作位置和通道的大小。

  ◆long position():返回目前的位置;

  ◆long size():返回通道连接实体的当前大小,如通道连接的文件大小;

  ◆position(long newPosition):移动当前位置到某个地方;

  ◆truncate(long size):根据给定大小截断实体。

  position()和truncate()方法简单地返回当前通道,允许链式调用。现在FileChannel实现了新的接口,使用所有FileChannel你都可以实现随机访问,当然你可以用它读取一个文件:

  3.SeekableByteChannel channel = null;

  4.try {

  5. channel = Paths.get(“Path to file”).newByteChannel(StandardOpenOption.READ);

  6. ByteBuffer buf = ByteBuffer.allocate(4096);

  7.

  8. System.out.println(“File size: ” + channel.size());

  9.

  10. String encoding = System.getProperty(“file.encoding”);

  11.

  12. while (channel.read(buf) > 0) {

  13. buf.rewind();

  14.

  15. byte[] bytearr = new byte[bytebuff.remaining()];

  16. buf.get(bytearray);

  17. System.out.print(new String(bytearray));

  18.

  19. buf.flip();

  20.

  21. System.out.println(“Current position : ” + channel.position());

  22. }

  23.} catch (IOException e) {

  24. System.out.println(“Expection when reading : ” + e.getMessage());

  25. e.printStackTrace();

  26.} finally {

  27. if (sbc != null){

  28. channel.close();

  29. }

  30.}

  MulticastChannel

  这个新的接口允许开启IP多播,因此你可以向一个完整的组发送和接收IP数据报。多播实现了直接绑定本地多播设备,这个接口是通过DatagramChannel和AsynchronousDatagramChannel实现的。下面是从Javadoc中摘取的一个打开DatagramChannel t的简单示例:

  1.NetworkInterface networkInterface = NetworkInterface.getByName(“hme0”);

  2.DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET)

  3. .setOption(StandardSocketOption.SO_REUSEADDR, true)

  4. .bind(new InetSocketAddress(5000))

  5. .setOption(StandardSocketOption.IP_MULTICAST_IF, networkInterface);

  6.

  7.InetAddress group = InetAddress.getByName(“225.4.5.6”);

  8.MembershipKey key = dc.join(group, networkInterface);

  你可以使用以前经常使用的DatagramChannel,但操作方式是多播了,因此你收到的是接口中所有的数据包,你发送的数据包会发到所有组。

[1][2]

然后继续努力,把让自己跌倒的石头搬掉或绕过去,不就解决问题了吗

Java 7 I/O新功能探秘:同步操作,多播与随机存取

相关文章:

你感兴趣的文章:

标签云: