java中io以及nio的基本案例

1、java中io和nio的区别个人理解,主要在于io是面向流,而nio是面向缓冲区的,io(bio)同步阻塞式的输入输出,而nio是同步非阻塞式的输出输出。


2、io复制文件代码

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class IoTest {

	public static void main(String[] args) {
		//创建一个输入流和输出流的引用
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			//初始化输入流和输出流
			inputStream = new FileInputStream("D:\\text.txt");
			outputStream = new FileOutputStream("D:\\text3.txt");
			//每次读取的字节流数组大小设置为1024
			byte bytes[] = new byte[1024];
			//读取到的长度
			int len = -1;
			//长度为-1则表示读到了文件的末尾
			while((len = inputStream.read(bytes))!=-1){
				//输出到指定文件中
				outputStream.write(bytes,0,len);
				//刷新缓存区
				outputStream.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			//关闭流
			try {
				if(outputStream!=null){
					outputStream.close();
				}
				if(inputStream!=null){
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
}


3、nio复制文件的代码

public class NioTest {

	public static void main(String[] args) throws Exception{
		//得到文件输入流
		FileInputStream fileInputStream = new FileInputStream(new File("D:\\text.txt"));
		//得到输入Channel通道
		FileChannel inChannel = fileInputStream.getChannel();
		//得到bytebuffer缓冲区
		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
		//得到输出流
		FileOutputStream fileOutputStream = new FileOutputStream("D:\\text3.txt");
		//得到输出通道
		FileChannel outChanner = fileOutputStream.getChannel();
		int eof = -1;
		//如果读取到的长度不为-1则缓冲区有数据
		while((eof=inChannel.read(byteBuffer))!=-1){
			//从读模式切换到写模式
			byteBuffer.flip();
			//写入到指定文件
			outChanner.write(byteBuffer);
			//清空缓冲区
			byteBuffer.clear();
		}
		//关闭通道和输入输出流
		outChanner.close();
		fileOutputStream.close();
		inChannel.close();
		fileInputStream.close();
	}
}


4、nio的好处在于nio是同步非阻塞式的,具体实现在于一个线程可以管理一个selector,然后可以有多个channel通道注册到该selector上,相当于一个线程控制一个selector选择器可以同时监听多个channel通道,一旦该通道的缓冲区有新的io请求,可以对该请求进行处理,而io流是同步阻塞式的,一个请求必须处理完成才能处理下一个请求,传统的tomcat就是使用的bio同步阻塞流方式处理客户端的请求,效率相对nio要低一些。 下面是nio的请求模型:


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java NIO (New IO) 是Java SE 1.4引入的一个新的IO API,可以用来替代Java标准IOJava网络编程的Socket和ServerSocket。Java NIO提供了非阻塞式的IO操作,可以实现更高效的网络编程。 以下是Java NIO的一个使用案例: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Scanner; public class NIOServer { public static void main(String[] args) throws IOException { // 创建ServerSocketChannel并绑定端口 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(9999)); serverSocketChannel.configureBlocking(false); System.out.println("NIOServer started on port 9999"); // 创建一个ByteBuffer用于读取数据 ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { // 接收客户端连接 SocketChannel socketChannel = serverSocketChannel.accept(); if (socketChannel != null) { System.out.println("Client connected from " + socketChannel.getRemoteAddress()); // 读取客户端发送的数据 int bytesRead = socketChannel.read(buffer); while (bytesRead != -1) { buffer.flip(); while (buffer.hasRemaining()) { System.out.print((char) buffer.get()); } buffer.clear(); bytesRead = socketChannel.read(buffer); } socketChannel.close(); } // 处理控制台输入 Scanner scanner = new Scanner(System.in); String message = scanner.nextLine(); if (message.equals("quit")) { break; } } // 关闭ServerSocketChannel serverSocketChannel.close(); } } ``` 该程序实现了一个简单的NIO服务器,它监听9999端口,接收客户端连接并读取客户端发送的数据。程序通过一个无限循环来保持运行,可以通过控制台输入"quit"来退出程序。在程序运行过程,可以使用telnet命令来模拟客户端连接并发送数据: ``` telnet localhost 9999 ``` 输入数据后,按下Enter键,然后可以在服务器控制台上看到客户端发送的数据。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值