JAVA BIO,JAVA NOI案列
一、Java BIO 案列
1、BIO 读取文件
import java.io.File;
import java.io.FileInputStream;
public class ReadFileBIO {
public static void main(String[] args) {
File file = new File("BIO.txt");
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[1024];
while (fileInputStream.read(bytes) != -1) {
System.out.printf(new String(bytes).trim());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
2、BIO 写文件
import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
public class WriteFileBIO {
public static void main(String[] args) {
String txt = "同步并阻塞(传统阻塞型),服务器实现模式为一个连接对应一个线程。及客户端有连接请求时,服务器就启动一个线程进行处理,当这个连接不做任何操作时(读写),线程会一直等待客户端的读写请求,等待(阻塞)的这段时间对线程资源造成很大的开销,浪费线程资源";
File file = new File("BIO.txt");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
byte[] bytes = txt.getBytes(StandardCharsets.UTF_8);
fileOutputStream.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
3、BIO文件拷贝
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class ReadWriteFileBIO {
public static void main(String[] args) {
//源文件
File inputFile = new File("BIO.txt");
//目标文件
File outputFile = new File("BIO2.txt");
//文件输入流
FileInputStream fileInputStream = null;
//文件输出流
FileOutputStream fileOutputStream = null;
try {
//文件输入流实例化
fileInputStream = new FileInputStream(inputFile);
//文件输出流实例化
fileOutputStream = new FileOutputStream(outputFile);
//创建byte数组
byte[] bytes = new byte[1024];
//循环读取输入流的数据到byte数组,然后将byte数组的数据写到输出流
while (true){
//读取输入流的数据到byte数组
int read = fileInputStream.read(bytes);
//判断输入流数据是否读取完毕,读取完毕退出循环
if (read == -1){
break;
}
//将byte数组的数据写到输出流
fileOutputStream.write(bytes);
}
} catch (Exception e) {
//异常处理
e.printStackTrace();
} finally {
//流关闭
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
4、BIO 网络编程案列
(1)BIO 服务端
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BIOServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
serverSocket = new ServerSocket(6666);
System.out.println("服务器启动了...");
while (true) {
System.out.println("等待客户端连接...");
Socket socket = serverSocket.accept();
System.out.println("连接到一个客户端...");
newCachedThreadPool.execute(new Runnable() {
@Override
public void run() {
messageHandler(socket);
}
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("服务器关闭...");
if (serverSocket != null) {
try {
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void messageHandler(Socket socket) {
byte[] bytes = new byte[1024];
InputStream inputStream = null;
try {
inputStream = socket.getInputStream();
while (true) {
int read = inputStream.read(bytes);
if (read != -1) {
System.out.println(new String(bytes, 0, read));
} else {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("关闭与客户端的连接...");
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
(2)BIO 客户端
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class BIOClient {
public static void main(String[] args) {
String username = "张三 : ";
Socket socket = null;
OutputStream outputStream = null;
try {
System.out.println("连接服务器...");
socket = new Socket("127.0.0.1", 6666);
System.out.println("服务器已连接");
Scanner scanner = new Scanner(System.in);
System.out.println("请输入信息:");
while (scanner.hasNext()){
String message = scanner.nextLine();
outputStream = socket.getOutputStream();
message = username + message;
byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
outputStream.write(bytes);
System.out.println("请输入信息:");
}
} catch (Exception e){
e.printStackTrace();
} finally {
System.out.println("关闭与服务器端的连接...");
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
二、Java NIO 案列
1、NIO读取文件
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ReadFileNIO {
public static void main(String[] args) {
File file = new File("NIO.txt");
FileInputStream fileInputStream = null;
FileChannel fileChannel = null;
try {
fileInputStream = new FileInputStream(file);
fileChannel = fileInputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (true) {
byteBuffer.clear();
int read = fileChannel.read(byteBuffer);
if (read == -1) {
break;
}
byteBuffer.flip();
System.out.println(new String(byteBuffer.array(), 0, read));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileChannel != null) {
try {
fileChannel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
2、NIO写文件
package com.dashu.netty.demo.nio;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
public class WriteFileBIO {
public static void main(String[] args) {
String txt = "同步非阻塞,服务器实现模式为一个线程处理多个连接请求。即客户端发送的连接请求都会注册到多路复用器上,多轮复用器轮询到连接有I/O请求的就进行处理";
File file = new File("NIO.txt");
FileOutputStream fileOutputStream = null;
FileChannel fileChannel = null;
try {
fileOutputStream = new FileOutputStream(file);
fileChannel = fileOutputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
byteBuffer.put(txt.getBytes(StandardCharsets.UTF_8));
byteBuffer.flip();
fileChannel.write(byteBuffer);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileChannel != null) {
try {
fileChannel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
3、NIO文件拷贝
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ReadWriteFileNIO {
public static void main(String[] args) {
File inputFile = new File("NIO.txt");
File outputFile = new File("NIO2.txt");
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
FileChannel inputFileChannel = null;
FileChannel outputFileChannel = null;
try {
fileInputStream = new FileInputStream(inputFile);
fileOutputStream = new FileOutputStream(outputFile);
inputFileChannel = fileInputStream.getChannel();
outputFileChannel = fileOutputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (true) {
byteBuffer.clear();
int read = inputFileChannel.read(byteBuffer);
if (read == -1) {
break;
}
byteBuffer.flip();
outputFileChannel.write(byteBuffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputFileChannel != null) {
try {
outputFileChannel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (inputFileChannel != null) {
try {
inputFileChannel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
4、NIO网络编程
(1)NIO 服务端
package com.dashu.netty.demo.nio.socket;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class NIOServer {
public static void main(String[] args) {
ServerSocketChannel serverSocketChannel = null;
SocketChannel socketChannel = null;
try {
serverSocketChannel = ServerSocketChannel.open();
InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
serverSocketChannel.socket().bind(inetSocketAddress);
serverSocketChannel.configureBlocking(false);
Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("启动服务器成功...");
System.out.println("等待客户端连接...");
while (true) {
if (selector.select() == 0) {
continue;
}
Set<SelectionKey> selectionKeySet = selector.selectedKeys();
Iterator<SelectionKey> selectionKeyIterator = selectionKeySet.iterator();
while (selectionKeyIterator.hasNext()) {
SelectionKey selectionKey = selectionKeyIterator.next();
if (selectionKey.isAcceptable()) {
socketChannel = serverSocketChannel.accept();
System.out.println("客户端连接成功... socketChannel = " + socketChannel.hashCode());
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
}
if (selectionKey.isReadable()) {
socketChannel = (SocketChannel) selectionKey.channel();
ByteBuffer byteBuffer = (ByteBuffer) selectionKey.attachment();
socketChannel.read(byteBuffer);
System.out.println("客户端" + socketChannel.hashCode() + "发来信息:" + new String(byteBuffer.array(), 0, byteBuffer.position()));
}
selectionKeyIterator.remove();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socketChannel != null) {
try {
socketChannel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (serverSocketChannel != null) {
try {
serverSocketChannel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
(2)NIO 客户端
package com.dashu.netty.demo.nio.socket;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class NIOClient {
public static void main(String[] args) {
SocketChannel socketChannel = null;
try {
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
boolean flag = socketChannel.connect(inetSocketAddress);
if (!flag) {
while (!socketChannel.finishConnect()) {
System.out.println("因为连接需要事件,客户端不会阻塞,可以做其他工作");
}
System.out.println("连接服务器成功...");
}
Scanner scanner = new Scanner(System.in);
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
System.out.println("请输入请求服务器的信息:");
while (scanner.hasNext()) {
String message = scanner.nextLine();
byteBuffer.clear();
byteBuffer.put(message.getBytes(StandardCharsets.UTF_8));
byteBuffer.flip();
socketChannel.write(byteBuffer);
System.out.println("请输入请求服务器的信息:");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socketChannel != null) {
try {
socketChannel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}