|
| 1 | +package com.brianway.java.nio.tutorial; |
| 2 | + |
| 3 | +import com.brianway.learning.java.nio.tutorial.BufferDemo; |
| 4 | +import org.junit.Assert; |
| 5 | +import org.junit.Test; |
| 6 | + |
| 7 | +import java.io.IOException; |
| 8 | +import java.io.RandomAccessFile; |
| 9 | +import java.nio.ByteBuffer; |
| 10 | +import java.nio.channels.FileChannel; |
| 11 | + |
| 12 | +/** |
| 13 | + * @auther brian |
| 14 | + * @since 2019/6/18 23:24 |
| 15 | + */ |
| 16 | +public class ScatterTest { |
| 17 | + |
| 18 | + private String path = BufferDemo.class.getResource("/").getPath() + "scatter.txt"; |
| 19 | + |
| 20 | + @Test |
| 21 | + public void testScatteringReads() throws IOException { |
| 22 | + RandomAccessFile aFile = new RandomAccessFile(path, "rw"); |
| 23 | + FileChannel fc = aFile.getChannel(); |
| 24 | + |
| 25 | + //create buffer with capacity of 48 bytes |
| 26 | + ByteBuffer header = ByteBuffer.allocate(8); |
| 27 | + ByteBuffer body = ByteBuffer.allocate(1024); |
| 28 | + |
| 29 | + ByteBuffer[] bufferArray = {header, body}; |
| 30 | + long bytesRead = fc.read(bufferArray); |
| 31 | + // System.out.println(bytesRead); |
| 32 | + Assert.assertEquals(26, bytesRead); |
| 33 | + //print header |
| 34 | + System.out.println("---header(" + header.limit() + "bytes)---"); |
| 35 | + header.flip(); |
| 36 | + while (header.hasRemaining()) { |
| 37 | + // read 1 byte at a time |
| 38 | + System.out.print((char) header.get()); |
| 39 | + } |
| 40 | + header.clear(); |
| 41 | + |
| 42 | + // print body |
| 43 | + body.flip(); |
| 44 | + System.out.println("---body(" + body.limit() + "bytes)----"); |
| 45 | + while (body.hasRemaining()) { |
| 46 | + // read 1 byte at a time |
| 47 | + System.out.print((char) body.get()); |
| 48 | + } |
| 49 | + header.clear(); |
| 50 | + body.clear(); |
| 51 | + fc.close(); |
| 52 | + } |
| 53 | +} |
0 commit comments