JavaNIO
一、IO與NIO
IO是一次性操作一個字節(jié)的數(shù)據(jù)進行讀寫操作。我們稱之為“面向流處理數(shù)據(jù)”
NIO是一次性操作一塊數(shù)據(jù)內容進行讀寫操作。我們稱之為“面向塊處理數(shù)據(jù)”
相比之下,面向塊處理數(shù)據(jù) 比 面向流處理數(shù)據(jù)效率高很多。
二、NIO核心
1、緩沖器 Buffer
Buffer是保存數(shù)據(jù)的地方,剛剛讀和寫的數(shù)據(jù)都是保存在Buffer當中,主要用于記錄系統(tǒng)讀寫的操作
2、通道 Channel
Channel是傳輸?shù)墓艿?,?shù)據(jù)會通過Buffer進行讀寫,真實的傳輸過程,由高效率的 Channel 管道幫忙傳輸
三、NIO的讀和寫
1、讀取操作
第一步: 獲取通道
FileInputStream fis = new FileInputStream("intext.txt");
FileChannel channel = fis.getChannel();
第二步:創(chuàng)建緩沖器
ByteBuffer buffer = ByteBuffer.allocate(1024);
第三步:建立聯(lián)系
int data = channel.read(buffer);
2、寫出操作
第一步:獲取通道
FileOutputStream fos = new FileOutputStream("outtext.txt");
FileChannel channel = fos.getChannel();
第二步:創(chuàng)建緩沖器
ByteBuffer buffer = ByteBuffer.allocate(1024);
第三步:建立聯(lián)系
buffer.put(new String("需要寫入的字符串").getBytes());
buffer.flip();
channel.write(buffer);