Skip to content

Commit

Permalink
[update] add ScatterTest from nio
Browse files Browse the repository at this point in the history
  • Loading branch information
brianway committed Jun 18, 2019
1 parent ad3c014 commit 2c8cdc8
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 1 deletion.
6 changes: 6 additions & 0 deletions java-io/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,10 @@

<artifactId>java-io</artifactId>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ public static void main(String[] args) throws IOException {

//make buffer ready for read
buf.flip();

while (buf.hasRemaining()) {
// read 1 byte at a time
System.out.print((char) buf.get());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package com.brianway.java.nio.tutorial;

import com.brianway.learning.java.nio.tutorial.BufferDemo;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
* @auther brian
* @since 2019/6/18 23:24
*/
public class ScatterTest {

private String path = BufferDemo.class.getResource("/").getPath() + "scatter.txt";

@Test
public void testScatteringReads() throws IOException {
RandomAccessFile aFile = new RandomAccessFile(path, "rw");
FileChannel fc = aFile.getChannel();

//create buffer with capacity of 48 bytes
ByteBuffer header = ByteBuffer.allocate(8);
ByteBuffer body = ByteBuffer.allocate(1024);

ByteBuffer[] bufferArray = {header, body};
long bytesRead = fc.read(bufferArray);
// System.out.println(bytesRead);
Assert.assertEquals(26, bytesRead);
//print header
System.out.println("---header(" + header.limit() + "bytes)---");
header.flip();
while (header.hasRemaining()) {
// read 1 byte at a time
System.out.print((char) header.get());
}
header.clear();

// print body
body.flip();
System.out.println("---body(" + body.limit() + "bytes)----");
while (body.hasRemaining()) {
// read 1 byte at a time
System.out.print((char) body.get());
}
header.clear();
body.clear();
fc.close();
}
}
3 changes: 3 additions & 0 deletions java-io/src/test/resources/scatter.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
1234567
qwertyusfdf
asdsad

0 comments on commit 2c8cdc8

Please sign in to comment.