|
| 1 | +### IO |
| 2 | +什么是IO? 它是指计算机与外部世界或者一个程序与计算机的其余部分的之间的接口。它对于任何计算机系统都非常关键,因而所有 I/O 的主体实际上是内置在操作系统中的。单独的程序一般是让系统为它们完成大部分的工作。 |
| 3 | + |
| 4 | +在 Java 编程中,直到最近一直使用 流 的方式完成 I/O。所有 I/O 都被视为单个的字节的移动,通过一个称为 Stream 的对象一次移动一个字节。流 I/O 用于与外部世界接触。它也在内部使用,用于将对象转换为字节,然后再转换回对象。 |
| 5 | + |
| 6 | +### BIO |
| 7 | + |
| 8 | +Java BIO即Block I/O , 同步并阻塞的IO。 |
| 9 | + |
| 10 | +BIO就是传统的java.io包下面的代码实现。 |
| 11 | + |
| 12 | +### NIO |
| 13 | + |
| 14 | +什么是NIO? NIO 与原来的 I/O 有同样的作用和目的, 他们之间最重要的区别是数据打包和传输的方式。原来的 I/O 以流的方式处理数据,而 NIO 以块的方式处理数据。 |
| 15 | + |
| 16 | +面向流 的 I/O 系统一次一个字节地处理数据。一个输入流产生一个字节的数据,一个输出流消费一个字节的数据。为流式数据创建过滤器非常容易。链接几个过滤器,以便每个过滤器只负责单个复杂处理机制的一部分,这样也是相对简单的。不利的一面是,面向流的 I/O 通常相当慢。 |
| 17 | + |
| 18 | +一个 面向块 的 I/O 系统以块的形式处理数据。每一个操作都在一步中产生或者消费一个数据块。按块处理数据比按(流式的)字节处理数据要快得多。但是面向块的 I/O 缺少一些面向流的 I/O 所具有的优雅性和简单性。 |
| 19 | + |
| 20 | +### AIO |
| 21 | + |
| 22 | +Java AIO即Async非阻塞,是异步非阻塞的IO。 |
| 23 | + |
| 24 | +### 区别及联系 |
| 25 | + |
| 26 | +BIO (Blocking I/O):同步阻塞I/O模式,数据的读取写入必须阻塞在一个线程内等待其完成。这里假设一个烧开水的场景,有一排水壶在烧开水,BIO的工作模式就是, 叫一个线程停留在一个水壶那,直到这个水壶烧开,才去处理下一个水壶。但是实际上线程在等待水壶烧开的时间段什么都没有做。 |
| 27 | + |
| 28 | +NIO (New I/O):同时支持阻塞与非阻塞模式,但这里我们以其同步非阻塞I/O模式来说明,那么什么叫做同步非阻塞?如果还拿烧开水来说,NIO的做法是叫一个线程不断的轮询每个水壶的状态,看看是否有水壶的状态发生了改变,从而进行下一步的操作。 |
| 29 | + |
| 30 | +AIO ( Asynchronous I/O):异步非阻塞I/O模型。异步非阻塞与同步非阻塞的区别在哪里?异步非阻塞无需一个线程去轮询所有IO操作的状态改变,在相应的状态改变后,系统会通知对应的线程来处理。对应到烧开水中就是,为每个水壶上面装了一个开关,水烧开之后,水壶会自动通知我水烧开了。 |
| 31 | + |
| 32 | +### 各自适用场景 |
| 33 | + |
| 34 | +BIO方式适用于连接数目比较小且固定的架构,这种方式对服务器资源要求比较高,并发局限于应用中,JDK1.4以前的唯一选择,但程序直观简单易理解。 |
| 35 | + |
| 36 | +NIO方式适用于连接数目多且连接比较短(轻操作)的架构,比如聊天服务器,并发局限于应用中,编程比较复杂,JDK1.4开始支持。 |
| 37 | + |
| 38 | +AIO方式适用于连接数目多且连接比较长(重操作)的架构,比如相册服务器,充分调用OS参与并发操作,编程比较复杂,JDK7开始支持。 |
| 39 | + |
| 40 | +### 使用方式 |
| 41 | + |
| 42 | +#### 使用BIO实现文件的读取和写入。 |
| 43 | + |
| 44 | + |
| 45 | +``` |
| 46 | +
|
| 47 | + //Initializes The Object |
| 48 | + User1 user = new User1(); |
| 49 | + user.setName("hollis"); |
| 50 | + user.setAge(23); |
| 51 | + System.out.println(user); |
| 52 | +
|
| 53 | + //Write Obj to File |
| 54 | + ObjectOutputStream oos = null; |
| 55 | + try { |
| 56 | + oos = new ObjectOutputStream(new FileOutputStream("tempFile")); |
| 57 | + oos.writeObject(user); |
| 58 | + } catch (IOException e) { |
| 59 | + e.printStackTrace(); |
| 60 | + } finally { |
| 61 | + IOUtils.closeQuietly(oos); |
| 62 | + } |
| 63 | +
|
| 64 | + //Read Obj from File |
| 65 | + File file = new File("tempFile"); |
| 66 | + ObjectInputStream ois = null; |
| 67 | + try { |
| 68 | + ois = new ObjectInputStream(new FileInputStream(file)); |
| 69 | + User1 newUser = (User1) ois.readObject(); |
| 70 | + System.out.println(newUser); |
| 71 | + } catch (IOException e) { |
| 72 | + e.printStackTrace(); |
| 73 | + } catch (ClassNotFoundException e) { |
| 74 | + e.printStackTrace(); |
| 75 | + } finally { |
| 76 | + IOUtils.closeQuietly(ois); |
| 77 | + try { |
| 78 | + FileUtils.forceDelete(file); |
| 79 | + } catch (IOException e) { |
| 80 | + e.printStackTrace(); |
| 81 | + } |
| 82 | + } |
| 83 | +
|
| 84 | + //Initializes The Object |
| 85 | + User1 user = new User1(); |
| 86 | + user.setName("hollis"); |
| 87 | + user.setAge(23); |
| 88 | + System.out.println(user); |
| 89 | +
|
| 90 | + //Write Obj to File |
| 91 | + ObjectOutputStream oos = null; |
| 92 | + try { |
| 93 | + oos = new ObjectOutputStream(new FileOutputStream("tempFile")); |
| 94 | + oos.writeObject(user); |
| 95 | + } catch (IOException e) { |
| 96 | + e.printStackTrace(); |
| 97 | + } finally { |
| 98 | + IOUtils.closeQuietly(oos); |
| 99 | + } |
| 100 | +
|
| 101 | + //Read Obj from File |
| 102 | + File file = new File("tempFile"); |
| 103 | + ObjectInputStream ois = null; |
| 104 | + try { |
| 105 | + ois = new ObjectInputStream(new FileInputStream(file)); |
| 106 | + User1 newUser = (User1) ois.readObject(); |
| 107 | + System.out.println(newUser); |
| 108 | + } catch (IOException e) { |
| 109 | + e.printStackTrace(); |
| 110 | + } catch (ClassNotFoundException e) { |
| 111 | + e.printStackTrace(); |
| 112 | + } finally { |
| 113 | + IOUtils.closeQuietly(ois); |
| 114 | + try { |
| 115 | + FileUtils.forceDelete(file); |
| 116 | + } catch (IOException e) { |
| 117 | + e.printStackTrace(); |
| 118 | + } |
| 119 | + } |
| 120 | +
|
| 121 | +``` |
| 122 | + |
| 123 | +#### 使用NIO实现文件的读取和写入。 |
| 124 | + |
| 125 | +``` |
| 126 | +
|
| 127 | +static void readNIO() { |
| 128 | + String pathname = "C:\\Users\\adew\\Desktop\\jd-gui.cfg"; |
| 129 | + FileInputStream fin = null; |
| 130 | + try { |
| 131 | + fin = new FileInputStream(new File(pathname)); |
| 132 | + FileChannel channel = fin.getChannel(); |
| 133 | +
|
| 134 | + int capacity = 100;// 字节 |
| 135 | + ByteBuffer bf = ByteBuffer.allocate(capacity); |
| 136 | + System.out.println("限制是:" + bf.limit() + "容量是:" + bf.capacity() |
| 137 | + + "位置是:" + bf.position()); |
| 138 | + int length = -1; |
| 139 | +
|
| 140 | + while ((length = channel.read(bf)) != -1) { |
| 141 | +
|
| 142 | + /* |
| 143 | + * 注意,读取后,将位置置为0,将limit置为容量, 以备下次读入到字节缓冲中,从0开始存储 |
| 144 | + */ |
| 145 | + bf.clear(); |
| 146 | + byte[] bytes = bf.array(); |
| 147 | + System.out.write(bytes, 0, length); |
| 148 | + System.out.println(); |
| 149 | +
|
| 150 | + System.out.println("限制是:" + bf.limit() + "容量是:" + bf.capacity() |
| 151 | + + "位置是:" + bf.position()); |
| 152 | +
|
| 153 | + } |
| 154 | +
|
| 155 | + channel.close(); |
| 156 | +
|
| 157 | + } catch (FileNotFoundException e) { |
| 158 | + e.printStackTrace(); |
| 159 | + } catch (IOException e) { |
| 160 | + e.printStackTrace(); |
| 161 | + } finally { |
| 162 | + if (fin != null) { |
| 163 | + try { |
| 164 | + fin.close(); |
| 165 | + } catch (IOException e) { |
| 166 | + e.printStackTrace(); |
| 167 | + } |
| 168 | + } |
| 169 | + } |
| 170 | + } |
| 171 | +
|
| 172 | + static void writeNIO() { |
| 173 | + String filename = "out.txt"; |
| 174 | + FileOutputStream fos = null; |
| 175 | + try { |
| 176 | +
|
| 177 | + fos = new FileOutputStream(new File(filename)); |
| 178 | + FileChannel channel = fos.getChannel(); |
| 179 | + ByteBuffer src = Charset.forName("utf8").encode("你好你好你好你好你好"); |
| 180 | + // 字节缓冲的容量和limit会随着数据长度变化,不是固定不变的 |
| 181 | + System.out.println("初始化容量和limit:" + src.capacity() + "," |
| 182 | + + src.limit()); |
| 183 | + int length = 0; |
| 184 | +
|
| 185 | + while ((length = channel.write(src)) != 0) { |
| 186 | + /* |
| 187 | + * 注意,这里不需要clear,将缓冲中的数据写入到通道中后 第二次接着上一次的顺序往下读 |
| 188 | + */ |
| 189 | + System.out.println("写入长度:" + length); |
| 190 | + } |
| 191 | +
|
| 192 | + } catch (FileNotFoundException e) { |
| 193 | + e.printStackTrace(); |
| 194 | + } catch (IOException e) { |
| 195 | + e.printStackTrace(); |
| 196 | + } finally { |
| 197 | + if (fos != null) { |
| 198 | + try { |
| 199 | + fos.close(); |
| 200 | + } catch (IOException e) { |
| 201 | + e.printStackTrace(); |
| 202 | + } |
| 203 | + } |
| 204 | + } |
| 205 | + } |
| 206 | +
|
| 207 | +``` |
| 208 | + |
| 209 | +#### 使用AIO实现文件的读取和写入 |
| 210 | + |
| 211 | +``` |
| 212 | +public class ReadFromFile { |
| 213 | + public static void main(String[] args) throws Exception { |
| 214 | + Path file = Paths.get("/usr/a.txt"); |
| 215 | + AsynchronousFileChannel channel = AsynchronousFileChannel.open(file); |
| 216 | +
|
| 217 | + ByteBuffer buffer = ByteBuffer.allocate(100_000); |
| 218 | + Future<Integer> result = channel.read(buffer, 0); |
| 219 | +
|
| 220 | + while (!result.isDone()) { |
| 221 | + ProfitCalculator.calculateTax(); |
| 222 | + } |
| 223 | + Integer bytesRead = result.get(); |
| 224 | + System.out.println("Bytes read [" + bytesRead + "]"); |
| 225 | + } |
| 226 | +} |
| 227 | +class ProfitCalculator { |
| 228 | + public ProfitCalculator() { |
| 229 | + } |
| 230 | + public static void calculateTax() { |
| 231 | + } |
| 232 | +} |
| 233 | +
|
| 234 | +public class WriteToFile { |
| 235 | +
|
| 236 | + public static void main(String[] args) throws Exception { |
| 237 | + AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open( |
| 238 | + Paths.get("/asynchronous.txt"), StandardOpenOption.READ, |
| 239 | + StandardOpenOption.WRITE, StandardOpenOption.CREATE); |
| 240 | + CompletionHandler<Integer, Object> handler = new CompletionHandler<Integer, Object>() { |
| 241 | +
|
| 242 | + @Override |
| 243 | + public void completed(Integer result, Object attachment) { |
| 244 | + System.out.println("Attachment: " + attachment + " " + result |
| 245 | + + " bytes written"); |
| 246 | + System.out.println("CompletionHandler Thread ID: " |
| 247 | + + Thread.currentThread().getId()); |
| 248 | + } |
| 249 | +
|
| 250 | + @Override |
| 251 | + public void failed(Throwable e, Object attachment) { |
| 252 | + System.err.println("Attachment: " + attachment + " failed with:"); |
| 253 | + e.printStackTrace(); |
| 254 | + } |
| 255 | + }; |
| 256 | +
|
| 257 | + System.out.println("Main Thread ID: " + Thread.currentThread().getId()); |
| 258 | + fileChannel.write(ByteBuffer.wrap("Sample".getBytes()), 0, "First Write", |
| 259 | + handler); |
| 260 | + fileChannel.write(ByteBuffer.wrap("Box".getBytes()), 0, "Second Write", |
| 261 | + handler); |
| 262 | +
|
| 263 | + } |
| 264 | +} |
| 265 | +``` |
0 commit comments