/* 字节IO */ public void byteIO() throws FileNotFoundException, IOException { FileInputStream fin = new FileInputStream(new File( "D:\\test\\byteio_in.txt")); FileOutputStream fout = new FileOutputStream(new File( "D:\\test\\byteio_out.txt")); int c = -1; while ((c = fin.read()) != -1) { fout.write(c); } fin.close(); fout.close(); } /* 字符IO */ public void charIO() throws FileNotFoundException, IOException { FileReader reader = new FileReader(new File("D:\\test\\chario_in.txt", "")); FileWriter writer = new FileWriter(new File("D:\\test\\chario_out.txt")); char[] charArr = new char[512]; while (reader.read(charArr) != -1) { writer.write(charArr); } reader.close(); writer.close(); } /* bufferIO */ public void bufferIO() throws FileNotFoundException, IOException { BufferedInputStream bufferReader = new BufferedInputStream( new FileInputStream("D:\\test\\bufferio_in.txt")); BufferedOutputStream bufferWriter = new BufferedOutputStream( new FileOutputStream("D:\\test\\bufferio_out.txt")); int c = -1; while ((c = bufferReader.read()) != -1) { bufferWriter.write(c); } bufferReader.close(); bufferWriter.close(); }
/* NIO */ public void NIO() throws FileNotFoundException, IOException { FileInputStream fin = new FileInputStream("D:\\test\\nio_in.txt"); FileOutputStream fout = new FileOutputStream("D:\\test\\nio_out.txt"); FileChannel finChannel = fin.getChannel(); FileChannel foutChannel = fout.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(512); while (finChannel.read(buffer) != 1)//读到缓存 { buffer.flip();//指针跳到缓存头 foutChannel.write(buffer); buffer.clear();//重置缓冲区 } fin.close(); fout.close(); }
Java自1.4以后,加入了新IO特性NIO,NIO带来了non-blocking特性。
在之前的服务器处理模型中,在调用ServerSocket.accept()方法时,会一直阻塞到有客户端连接才会返回,每个客户端连接过来后,服务端都会accept一个新连接,接着启动一个线程去处理该客户端的请求。在这个新的线程中,也会在read()方法中阻塞,指导读取完数据。
这样会有什么问题呢?
阻塞导致大量线程资源被浪费;阻塞可导致大量的上下文切换,很多切换其实是无意义的
那么NIO是如何帮助我们解决这种问题的呢?
使用异步 I/O,您可以监听任何数量的通道上的事件,不用轮询,也不用额外的线程。
原文:http://www.cnblogs.com/mingziday/p/4992998.html