Skip to content

Commit 2c8cdc8

Browse files
committed
[update] add ScatterTest from nio
1 parent ad3c014 commit 2c8cdc8

File tree

4 files changed

+62
-1
lines changed

4 files changed

+62
-1
lines changed

java-io/pom.xml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,10 @@
1111

1212
<artifactId>java-io</artifactId>
1313

14+
<dependencies>
15+
<dependency>
16+
<groupId>junit</groupId>
17+
<artifactId>junit</artifactId>
18+
</dependency>
19+
</dependencies>
1420
</project>

java-io/src/main/java/com/brianway/learning/java/nio/tutorial/BufferDemo.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ public static void main(String[] args) throws IOException {
2626

2727
//make buffer ready for read
2828
buf.flip();
29-
3029
while (buf.hasRemaining()) {
3130
// read 1 byte at a time
3231
System.out.print((char) buf.get());
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
1234567
2+
qwertyusfdf
3+
asdsad

0 commit comments

Comments
 (0)