Skip to content

Commit

Permalink
added nio.
Browse files Browse the repository at this point in the history
  • Loading branch information
T5750 committed Sep 7, 2018
1 parent 1c43415 commit ede5991
Show file tree
Hide file tree
Showing 19 changed files with 692 additions and 2 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ java-repositories/
│ ├── [v0.8.2] dsa
│ ├── [v0.8.3] aes
│ └── [v0.8.4] https
└── [v0.9] blockchain
└── NoobChainTutorial
├── [v0.9] blockchain
│ └── NoobChainTutorial
└── [v0.10] nio
```

## License
Expand Down
62 changes: 62 additions & 0 deletions nio/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Java NIO

## Java NIO Tutorial
### Java NIO
Java NIO基本组件如下:

![NIO-Components](http://www.wailian.work/images/2018/09/07/NIO-Components.png)

### NIO Components

### NIO Package

### NIO vs. IO
Java IO和NIO之间的主要区别:

IO | NIO
------|------
基于阻塞I/O操作 | 基于非阻塞I/O操作
面向流的 | 面向缓存的
通道不可用 | 通道可用于非阻塞I/O操作
选择器不可用 | 选择器可用于非阻塞I/O操作

通道和流之间的主要区别是:
- 流可以用于单向数据传输
- 通道提供双向数据传输

### NIO Channels
- `ChannelDemo`

### NIO Buffers
- `BufferedReaderDemo`

### NIO Scatter/Gather
- `ScatterGatherIO`

### NIO Data Transfer
- `TransferDemo`

### NIO Selector
- `SelectorExample`
- `Client`

### NIO SocketChannel

### NIO ServerSocketChannel

### NIO Pipe
- `PipeExample`

### NIO CharSet
- `CharsetExample`

### NIO Encode/Decode
- `CharsetExam`

### NIO Channels FileLock
- `FileLockExample`
- `PrintFile`

## Links
- [Java NIO教程](https://www.yiibai.com/java_nio/)
- [Java NIO Tutorial](https://www.javatpoint.com/java-nio)
15 changes: 15 additions & 0 deletions nio/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>java-repositories</artifactId>
<groupId>com.evangel</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>nio</artifactId>


</project>
39 changes: 39 additions & 0 deletions nio/src/main/java/com/yiibai/BufferedReaderDemo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.yiibai;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.yiibai.util.Global;

/**
* 使用BufferedReader从testin.txt文件中读取行
*/
public class BufferedReaderDemo {
public static void main(String[] args) {
Path file = null;
BufferedReader bufferedReader = null;
String relativelyPath = System.getProperty("user.dir");
try {
file = Paths.get(relativelyPath + Global.PROJECT_DIR
+ "/testin.txt");
InputStream inputStream = Files.newInputStream(file);
bufferedReader = new BufferedReader(new InputStreamReader(
inputStream));
System.out.println("Reading the Line of testin.txt file: \n"
+ bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
43 changes: 43 additions & 0 deletions nio/src/main/java/com/yiibai/ChannelDemo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.yiibai;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

import com.yiibai.util.Global;

/**
* 将数据从一个通道复制到另一个通道或从一个文件复制到另一个文件
*/
public class ChannelDemo {
public static void main(String args[]) throws IOException {
String relativelyPath = System.getProperty("user.dir");
FileInputStream input = new FileInputStream(relativelyPath
+ Global.PROJECT_DIR + "/testin.txt");
ReadableByteChannel source = input.getChannel();
FileOutputStream output = new FileOutputStream(relativelyPath
+ Global.PROJECT_DIR + "/testout.txt");
WritableByteChannel destination = output.getChannel();
copyData(source, destination);
source.close();
destination.close();
System.out.println("Copy Data finished.");
}

private static void copyData(ReadableByteChannel src,
WritableByteChannel dest) throws IOException {
ByteBuffer buffer = ByteBuffer.allocateDirect(20 * 1024);
while (src.read(buffer) != -1) {
// The buffer is used to drained
buffer.flip();
// keep sure that buffer was fully drained
while (buffer.hasRemaining()) {
dest.write(buffer);
}
buffer.clear(); // Now the buffer is empty, ready for the filling
}
}
}
28 changes: 28 additions & 0 deletions nio/src/main/java/com/yiibai/CharsetExam.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.yiibai;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

/**
* 基本编码和解码示例
*/
public class CharsetExam {
public static void main(String[] args) throws CharacterCodingException {
Charset cs = Charset.forName("UTF-8");
CharsetDecoder csdecoder = cs.newDecoder();
CharsetEncoder csencoder = cs.newEncoder();
String st = "Example of Encode and Decode in Java NIO.";
ByteBuffer bb = ByteBuffer.wrap(st.getBytes());
CharBuffer cb = csdecoder.decode(bb);
ByteBuffer newbb = csencoder.encode(cb);
while (newbb.hasRemaining()) {
char ca = (char) newbb.get();
System.out.print(ca);
}
newbb.clear();
}
}
29 changes: 29 additions & 0 deletions nio/src/main/java/com/yiibai/CharsetExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.yiibai;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

/**
* 基本字符串示例
*/
public class CharsetExample {
public static void main(String[] args) {
Charset cs = Charset.forName("UTF-8");
System.out.println(cs.displayName());
System.out.println(cs.canEncode());
String st = "Welcome to yiibai.com, it is Charset test Example.";
// The conversion of byte buffer from given charset to char buffer in
// unicode
ByteBuffer bytebuffer = ByteBuffer.wrap(st.getBytes());
CharBuffer charbuffer = cs.decode(bytebuffer);
// The converesion of char buffer from unicode to byte buffer in given
// charset
ByteBuffer newbytebuffer = cs.encode(charbuffer);
while (newbytebuffer.hasRemaining()) {
char ca = (char) newbytebuffer.get();
System.out.print(ca);
}
newbytebuffer.clear();
}
}
30 changes: 30 additions & 0 deletions nio/src/main/java/com/yiibai/Client.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.yiibai;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
* 基本选择器
*/
public class Client {
public static void main(String[] args) throws IOException,
InterruptedException {
InetSocketAddress hA = new InetSocketAddress("localhost", 8080);
SocketChannel client = SocketChannel.open(hA);
System.out.println("The Client is sending messages to server...");
// Sending messages to the server
String[] msg = new String[] { "Time goes fast.", "What next?",
"Bye Bye" };
for (int j = 0; j < msg.length; j++) {
byte[] message = new String(msg[j]).getBytes();
ByteBuffer buffer = ByteBuffer.wrap(message);
client.write(buffer);
System.out.println(msg[j]);
buffer.clear();
Thread.sleep(3000);
}
client.close();
}
}
36 changes: 36 additions & 0 deletions nio/src/main/java/com/yiibai/FileLockExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.yiibai;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import com.yiibai.util.Global;

/**
* 基本FileLock示例
*/
public class FileLockExample {
public static void main(String[] args) throws IOException {
String input = "* end of the file.";
System.out.println("Input string to the test file is: " + input);
ByteBuffer buf = ByteBuffer.wrap(input.getBytes());
String fp = Global.PATH_TESTOUT + "testin.txt";
Path pt = Paths.get(fp);
FileChannel fc = FileChannel.open(pt, StandardOpenOption.WRITE,
StandardOpenOption.APPEND);
System.out
.println("File channel is open for write and Acquiring lock...");
fc.position(fc.size() - 1); // position of a cursor at the end of file
FileLock lock = fc.lock();
System.out.println("The Lock is shared: " + lock.isShared());
fc.write(buf);
fc.close(); // Releases the Lock
System.out
.println("Content Writing is complete. Therefore close the channel and release the lock.");
PrintFile.print(fp);
}
}
38 changes: 38 additions & 0 deletions nio/src/main/java/com/yiibai/PipeExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.yiibai;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

/**
* 基本管道示例
*/
public class PipeExample {
public static void main(String[] args) throws IOException {
// The Pipe is created
Pipe pipe = Pipe.open();
// For accessing the pipe sink channel
Pipe.SinkChannel skChannel = pipe.sink();
String td = "Data is successfully sent for checking the java NIO Channel Pipe.";
ByteBuffer bb = ByteBuffer.allocate(512);
bb.clear();
bb.put(td.getBytes());
bb.flip();
// write the data into a sink channel.
while (bb.hasRemaining()) {
skChannel.write(bb);
}
// For accessing the pipe source channel
Pipe.SourceChannel sourceChannel = pipe.source();
bb = ByteBuffer.allocate(512);
// The data is write to the console
while (sourceChannel.read(bb) > 0) {
bb.flip();
while (bb.hasRemaining()) {
char TestData = (char) bb.get();
System.out.print(TestData);
}
bb.clear();
}
}
}
23 changes: 23 additions & 0 deletions nio/src/main/java/com/yiibai/PrintFile.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.yiibai;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
* 基本FileLock示例
*/
public class PrintFile {
public static void print(String path) throws IOException {
FileReader filereader = new FileReader(path);
BufferedReader bufferedreader = new BufferedReader(filereader);
String tr = bufferedreader.readLine();
System.out.println("The Content of testout-file.txt file is: ");
while (tr != null) {
System.out.println(" " + tr);
tr = bufferedreader.readLine();
}
filereader.close();
bufferedreader.close();
}
}

0 comments on commit ede5991

Please sign in to comment.