随着分布式技术的普及和海量数据的增长,io的能力越来越重要,java提供的io模块提供了足够的扩展性来适应。

我是李福春,我在准备面试,今天的问题是:

java中的io有哪几种?

java中的io分3类:

1,BIO ,即同步阻塞IO,对应java.io包提供的工具;基于流模型,虽然直观,代码实现也简单,但是扩展性差,消耗资源大,容易成为系统的瓶颈;

2,NIO,同步非阻塞io,对应java.nio包提供的工具,基于io多路复用;
核心类: Channel ,Selector , Buffer , Charset  
selector是io多路复用的基础,实现了一个线程高效管理多个客户端连接,通过事件监听处理感兴趣的事件。

3,AIO,即异步非阻塞io, 基于事件和回调

io的类层级

java各种IO的例子

java.io客户端连接服务端例子

package org.example.mianshi.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket; /**
* 说明:传统流式io 客户端连接服务端例子
* @author carter
* 创建时间: 2020年03月25日 9:58 下午
**/ public class JavaIOApp { public static void main(String[] args) { final Server server = new Server();
new Thread(server).start(); try (
Socket socket = new Socket(InetAddress.getLocalHost(), server.getPort());
) {
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); bufferedReader.lines().forEach(System.out::println); } catch (IOException e) {
e.printStackTrace();
}
} public static class Server implements Runnable { private ServerSocket serverSocket; public int getPort() {
return serverSocket.getLocalPort();
} @Override
public void run() { try (ServerSocket serverSocket = new ServerSocket(0);) { this.serverSocket = serverSocket;
while (true) {
final Socket socket = serverSocket.accept();
new RequestHandler(socket).start();
} } catch (IOException e) {
e.printStackTrace();
} } private class RequestHandler extends Thread {
private Socket socket; public RequestHandler(Socket socket) {
this.socket = socket;
} @Override
public void run() {
try (
final PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
) { printWriter.write("hello world");
printWriter.flush(); } catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

使用连接池优化

package org.example.mianshi.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; /**
* 说明:传统流式io 客户端连接服务端例子
* @author carter
* 创建时间: 2020年03月25日 9:58 下午
**/ public class ThreadPoolJavaIOApp { public static void main(String[] args) { final Server server = new Server();
new Thread(server).start(); try (
Socket socket = new Socket(InetAddress.getLocalHost(), server.getPort());
) {
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); bufferedReader.lines().forEach(System.out::println); } catch (IOException e) {
e.printStackTrace();
}
} public static class Server implements Runnable { private ExecutorService threadPool = Executors.newFixedThreadPool(4); private ServerSocket serverSocket; public int getPort() {
return serverSocket.getLocalPort();
} @Override
public void run() { try (ServerSocket serverSocket = new ServerSocket(0);) { this.serverSocket = serverSocket;
while (true) {
final Socket socket = serverSocket.accept(); threadPool.submit(new RequestHandler(socket));
} } catch (IOException e) {
e.printStackTrace();
}finally {
threadPool.shutdown();
} } private class RequestHandler implements Runnable {
private Socket socket; public RequestHandler(Socket socket) {
this.socket = socket;
} @Override
public void run() {
try (
final PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
) { printWriter.write("hello world");
printWriter.flush(); } catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

java.nio例子

package org.example.mianshi.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset; /**
* 说明:nio的客户端连接服务端例子
* @author carter
* 创建时间: 2020年03月25日 10:32 下午
**/ public class JavaNioApp { public static void main(String[] args) { new Server().start(); try (
Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
) {
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); bufferedReader.lines().forEach(System.out::println); } catch (IOException e) {
e.printStackTrace();
}
} public static class Server extends Thread { @Override
public void run() { try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.bind(new InetSocketAddress(InetAddress.getLocalHost(), 8888)); serverSocketChannel.configureBlocking(false); final Selector selector = Selector.open(); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); while (true) { selector.select();
selector.selectedKeys().forEach(selectionKey -> {
sayHelloWorld((ServerSocketChannel) selectionKey.channel());
}); } } catch (IOException e) {
e.printStackTrace();
} } private void sayHelloWorld(ServerSocketChannel channel) { try (SocketChannel socketChannel = channel.accept()) { socketChannel.write(Charset.defaultCharset().encode("hello world nio")); } catch (IOException e) {
e.printStackTrace();
} }
} }

![image.png](https://img2020.cnblogs.com/other/268922/202003/268922-20200325233150738-94393984.png)

java.nio2例子

package org.example.mianshi.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset; /**
* 说明:TODO
* @author carter
* 创建时间: 2020年03月25日 10:54 下午
**/ public class JavaNio2App { public static void main(String[] args) { new Server().start(); try (
Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
) {
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); bufferedReader.lines().forEach(System.out::println); } catch (IOException e) {
e.printStackTrace();
} } public static class Server extends Thread { @Override
public void run() { try {
AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open()
.bind(new InetSocketAddress(InetAddress.getLocalHost(), 9999)); serverSocketChannel.accept(serverSocketChannel, new CompletionHandler<AsynchronousSocketChannel, AsynchronousServerSocketChannel>() {
@Override
public void completed(AsynchronousSocketChannel socketChannel,
AsynchronousServerSocketChannel serverSocketChannel1) {
// serverSocketChannel1.accept(socketChannel, this); socketChannel.write(Charset.defaultCharset().encode("hello world nio2 ")); try {
socketChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
} @Override
public void failed(Throwable exc, AsynchronousServerSocketChannel attachment) {
exc.printStackTrace();
}
}); } catch (IOException e) {
e.printStackTrace();
} }
} }

本例子暂时无法运行。只为展示过程;

小结

本篇主要介绍了java提供的3中io,即 BIO,NIO,AIO ; 并提供了一些示例代码辅助理解。

原创不易,转载请注明出处。

面试刷题11:java系统中io的分类有哪些?的更多相关文章

  1. 面试刷题21:java并发工具中的队列有哪些?

    ![image.png](https://img2020.cnblogs.com/other/268922/202003/268922-20200330183801141-1514127119.png ...

  2. 安利一个基于Spring Cloud 的面试刷题系统。面试、毕设、项目经验一网打尽

    推荐: 接近100K star 的Java学习/面试指南 Github 95k+点赞的Java面试/学习手册.pdf 今天给小伙伴们推荐一个朋友开源的面试刷题系统. 这篇文章我会从系统架构设计层面详解 ...

  3. 牛客网刷题(纯java题型 1~30题)

    牛客网刷题(纯java题型 1~30题) 应该是先extend,然后implement class test extends A implements B { public static void m ...

  4. 牛客网刷题(纯java题型 31~60题)

    牛客网刷题(纯java题型 31~60题) 重写Override应该满足"三同一大一小"三同:方法名相同,参数列表相同,返回值相同或者子类的返回值是父类的子类(这一点是经过验证的) ...

  5. leetcode 刷题记录(java)-持续更新

    最新更新时间 11:22:29 8. String to Integer (atoi) public static int myAtoi(String str) { // 1字符串非空判断 " ...

  6. 最长绝对文件路径——算法面试刷题1(google),字符串处理,使用tree遍历dfs类似思路

    假设我们通过以下的方式用字符串来抽象我们的文件系统: 字符串"dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"代表了: dir subdir1 su ...

  7. 面试刷题28:如何写出安全的java代码?

    对jdk,jvm,java应用程序的攻击多种多样?那么从java程序员的角度,如何写出安全的代码呢? 我是李福春,我在准备面试,今天的题目是:如何写出安全的java代码? 答:这个需要从功能设计到实现 ...

  8. LeetCode随缘刷题之Java经典面试题将一个字符串数组进行分组输出,每组中的字符串都由相同的字符组成

    今天给大家分享一个Java经典的面试题,题目是这样的: 本题是LeetCode题库中的49题. 将一个字符串数组进行分组输出,每组中的字符串都由相同的字符组成 举个例子:输入["eat&qu ...

  9. 牛客网Java刷题知识点之父类中的私有内容,子类是否具备? 子类不可直接,但可间接访问父类中的私有内容?

    不多说,直接上干货!  父类中的私有内容,子类是否具备? 答:不具备 子类不可直接,但可间接访问父类中的私有内容 这样情况,开发中不所见,但是,面试的时候,必考非常常见.

随机推荐

  1. MySQL rand(随机数)、floor(保留整数)、char(ASCII 转字符)、concat(字符串连接)

    一.MySQL的rand()函数 select rand(); rand()函数,随机0-1之间的数. 二.获得0-10之间的整数(包含0,不包含10) ; 其中floor()去掉小数. 三.获得指定 ...

  2. 吴裕雄--天生自然KITTEN编程:忍者追宝

  3. 基于FPGA的RGB图像转灰度图像算法实现

    一.前言 最近学习牟新刚编著<基于FPGA的数字图像处理原理及应用>的第六章直方图操作,由于需要将捕获的图像转换为灰度图像,因此在之前代码的基础上加入了RGB图像转灰度图像的算法实现. 2 ...

  4. python xlwings Excel 内容截图

    import xlwings as xw from PIL import ImageGrab def excel_save_img(path, sheet=0, img_name="1&qu ...

  5. unittest实战(二):用例编写

    # coding:utf-8import unittestfrom selenium import webdriverimport timefrom ddt import ddt, data, unp ...

  6. 7-19 计算有n个字符串中最长的字符串长度 (40 分)

    编写程序,用于计算有n(1<n<10)个字符串中最长的字符串的长度.前导空格不要计算在内! 输入格式: 在第一行中输入n,接下的每行输入一个字符串 输出格式: 在一行中输出最长的字符串的长 ...

  7. 关于SSH与SSM的组成及其区别

    前言 当下SpringBoot盛行,咱再聊聊SpringBoot盛行之前的框架组合,当做复习巩固哈. 在聊之前,得先说说MVC,MVC全名是Model View Controller,是模型(mode ...

  8. An incompatible version [1.1.33] of the APR based Apache Tomcat Native library is installed, while Tomcat requires version [1.2.14]

    Springboot项目启动出现如下错误信息 解决办法在此地址:http://archive.apache.org/dist/tomcat/tomcat-connectors/native/1.2.1 ...

  9. vue 点击跳转路由设置

    刚接触 知道有两种方法,一种是用路由,一种是原生js的 <a @click="handleClick"></a> methods:function(){ h ...

  10. webstorm破解 2020 最新更新

    KNBB2QUUR1-eyJsaWNlbnNlSWQiOiJLTkJCMlFVVVIxIiwibGljZW5zZWVOYW1lIjoiZ2hib2tlIiwiYXNzaWduZWVOYW1lIjoiI ...