Skip to content

Commit 562a124

Browse files
committed
Difference between NIO and NIO.2?
1 parent 3ac64ce commit 562a124

2 files changed

Lines changed: 71 additions & 0 deletions

File tree

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package com.baeldung.niovsnio2;
2+
3+
import org.junit.Test;
4+
5+
import java.io.File;
6+
import java.io.FileInputStream;
7+
import java.io.RandomAccessFile;
8+
import java.nio.ByteBuffer;
9+
import java.nio.channels.FileChannel;
10+
import java.nio.file.Files;
11+
import java.nio.file.Path;
12+
import java.nio.file.Paths;
13+
import java.util.List;
14+
import java.util.stream.Stream;
15+
16+
import static org.assertj.core.api.Assertions.assertThat;
17+
18+
public class NioVsNio2UnitTest {
19+
20+
@Test
21+
public void readFromFileUsingFileIO() throws Exception {
22+
File file = new File("src/test/resources/nio-vs-nio2.txt");
23+
FileInputStream in = new FileInputStream(file);
24+
StringBuilder content = new StringBuilder();
25+
int data = in.read();
26+
while (data != -1) {
27+
content.append((char) data);
28+
data = in.read();
29+
}
30+
in.close();
31+
assertThat(content.toString()).isEqualTo("Hello from file!");
32+
}
33+
34+
@Test
35+
public void readFromFileUsingFileChannel() throws Exception {
36+
RandomAccessFile file = new RandomAccessFile("src/test/resources/nio-vs-nio2.txt", "r");
37+
FileChannel channel = file.getChannel();
38+
StringBuilder content = new StringBuilder();
39+
40+
ByteBuffer buffer = ByteBuffer.allocate(256);
41+
int bytesRead = channel.read(buffer);
42+
while (bytesRead != -1) {
43+
buffer.flip();
44+
45+
while (buffer.hasRemaining()) {
46+
content.append((char) buffer.get());
47+
}
48+
49+
buffer.clear();
50+
bytesRead = channel.read(buffer);
51+
}
52+
file.close();
53+
54+
assertThat(content.toString()).isEqualTo("Hello from file!");
55+
}
56+
57+
@Test
58+
public void readFromFileUsingNIO2() throws Exception {
59+
List<String> strings = Files.readAllLines(Paths.get("src/test/resources/nio-vs-nio2.txt"));
60+
61+
assertThat(strings.get(0)).isEqualTo("Hello from file!");
62+
}
63+
64+
@Test
65+
public void listFilesUsingWalk() throws Exception {
66+
Path path = Paths.get("src/test");
67+
Stream<Path> walk = Files.walk(path);
68+
walk.forEach(System.out::println);
69+
}
70+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Hello from file!

0 commit comments

Comments
 (0)