Java NIO是什么
Java NIO( New IO) 是從Java 1.4版本開(kāi)始引入的一個(gè)新的IO API执庐,可以替代標(biāo)準(zhǔn)的Java IO API。NIO與原來(lái)的IO有同樣的作用和目的导梆,但是使用的方式完全不同轨淌, NIO支持面向緩沖區(qū)的、基于通道的IO操作看尼。 NIO將以更加高效的方式進(jìn)行文件的讀寫(xiě)操作递鹉。
Java NIO 與 IO 的主要區(qū)別
IO | NIO |
---|---|
面向流(Stream Oriented) | 面向緩沖區(qū)(Buffer Oriented) |
阻塞IO(Blocking IO) | 非阻塞IO(Non Blocking IO) |
(無(wú)) | 選擇器(Selectors) |
緩沖區(qū)( Buffer)
一個(gè)用于特定基本數(shù)據(jù)類(lèi)型的容器。由 java.nio 包定義的藏斩,所有緩沖區(qū)都是 Buffer 抽象類(lèi)的子類(lèi)躏结。Buffer 主要用于與 NIO 通道進(jìn)行交互,數(shù)據(jù)是從通道讀入緩沖區(qū)灾茁,從緩沖區(qū)寫(xiě)入通道中的窜觉。Buffer 就像一個(gè)數(shù)組,可以保存多個(gè)相同類(lèi)型的數(shù)據(jù)北专。根據(jù)數(shù)據(jù)類(lèi)型不同(boolean 除外) 禀挫,有以下 Buffer 常用子類(lèi):
- ByteBuffer
- CharBuffer
- ShortBuffer
- IntBuffer
- LongBuffer
- FloatBuffer
- DoubleBuffer
上述 Buffer 類(lèi) 他們都采用相似的方法進(jìn)行管理數(shù)據(jù),只是各自管理的數(shù)據(jù)類(lèi)型不同而已拓颓。
緩沖區(qū)的基本屬性
- 容量 (capacity) :表示 Buffer 最大數(shù)據(jù)容量语婴,緩沖區(qū)容量不能為負(fù),并且創(chuàng)建后不能更改.
- 限制 (limit):第一個(gè)不應(yīng)該讀取或?qū)懭氲臄?shù)據(jù)的索引驶睦,即位于 limit 后的數(shù)據(jù)不可讀寫(xiě)砰左。緩沖區(qū)的限制不能為負(fù),并且不能大于其容量场航。
- 位置 (position):下一個(gè)要讀取或?qū)懭氲臄?shù)據(jù)的索引缠导。緩沖區(qū)的位置不能為負(fù),并且不能大于其限制.
- 標(biāo)記 (mark)與重置 (reset):標(biāo)記是一個(gè)索引溉痢,通過(guò) Buffer 中的 mark() 方法指定 Buffer 中一個(gè)特定的 position僻造,之后可以通過(guò)調(diào)用 reset()方法恢復(fù)到這個(gè) position.
標(biāo)記、 位置孩饼、 限制髓削、 容量遵守以下不變式: 0 <= mark <= position <= limit <= capacity
緩沖區(qū)的數(shù)據(jù)操作
Buffer 所有子類(lèi)提供了兩個(gè)用于數(shù)據(jù)操作的方法: get()與 put() 方法
獲取 Buffer 中的數(shù)據(jù)
- get() :讀取單個(gè)字節(jié)
- get(byte[] dst):批量讀取多個(gè)字節(jié)到 dst 中
- get(int index):讀取指定索引位置的字節(jié)(不會(huì)移動(dòng) position)
放入數(shù)據(jù)到 Buffer 中
- put(byte b):將給定單個(gè)字節(jié)寫(xiě)入緩沖區(qū)的當(dāng)前位置
- put(byte[] src):將 src 中的字節(jié)寫(xiě)入緩沖區(qū)的當(dāng)前位置
- put(int index, byte b):將指定字節(jié)寫(xiě)入緩沖區(qū)的索引位置(不會(huì)移動(dòng) position)
public class TestBuffer {
@Test
public void test1() {
//分配指定大小的緩沖區(qū)
ByteBuffer buffer = ByteBuffer.allocate(1024);
System.out.println(buffer.position());//0 返回緩沖區(qū)的當(dāng)前位置 position
System.out.println(buffer.limit());//1024 返回 Buffer 的界限(limit) 的位置
System.out.println(buffer.capacity());//1024 返回Buffer的capacity 大小
//將數(shù)據(jù)存入緩沖區(qū)
buffer.put("abcde".getBytes());
System.out.println(buffer.position());//5
System.out.println(buffer.limit());//1024
System.out.println(buffer.capacity());//1024
//切換到讀取數(shù)據(jù)的模式
buffer.flip();
System.out.println(buffer.position());//0
System.out.println(buffer.limit());//5
System.out.println(buffer.capacity());//1024
//讀取緩沖區(qū)的數(shù)據(jù)
byte[] bs = new byte[buffer.limit()];
buffer.get(bs);
System.out.println(new String(bs, 0, bs.length));//abcde
System.out.println(buffer.position());//5
System.out.println(buffer.limit());//5
System.out.println(buffer.capacity());//1024
//回到讀模式,可重復(fù)讀數(shù)據(jù)
buffer.rewind();//將位置設(shè)為為 0镀娶, 取消設(shè)置的 mark
System.out.println(buffer.position());//0
System.out.println(buffer.limit());//5
System.out.println(buffer.capacity());//1024
//清空緩沖區(qū)立膛,回到最初狀態(tài)。但是緩沖區(qū)的數(shù)據(jù)還在梯码,處于被遺忘狀態(tài)宝泵。
buffer.clear();//清空緩沖區(qū)并返回對(duì)緩沖區(qū)的引用
System.out.println(buffer.position());//0
System.out.println(buffer.limit());//1024
System.out.println(buffer.capacity());//1024
}
@Test
public void test2() {
String str = "abcde";
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put(str.getBytes());
System.out.println(buffer.position());//5
System.out.println(buffer.limit());//1024
System.out.println(buffer.capacity());//1024
buffer.flip();
byte[] bs = new byte[buffer.limit()];
buffer.get(bs, 0, 2);
System.out.println(new String(bs, 0, 2));//ab
System.out.println(buffer.position());//2
System.out.println(buffer.limit());//5
System.out.println(buffer.capacity());//1024
//標(biāo)記position的位置
buffer.mark();
buffer.get(bs, 2, 2);
System.out.println(new String(bs, 2, 2));//cd
System.out.println(buffer.position());//4
//重置position的位置到標(biāo)記的地方
buffer.reset();
System.out.println(buffer.position());//2
//緩沖區(qū)中是否還有課操作的字節(jié)
if (buffer.hasRemaining()) {
//剩余可操作的字節(jié)數(shù)
System.out.println(buffer.remaining());//3 返回 position 和 limit 之間的元素個(gè)數(shù)
}
}
@Test
public void test3() {
//創(chuàng)建直接緩沖區(qū)
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
//判斷是否為直接緩沖區(qū)
System.out.println(buffer.isDirect());//true
}
}
直接與非直接緩沖區(qū)
- 字節(jié)緩沖區(qū)要么是直接的好啰,要么是非直接的。如果為直接字節(jié)緩沖區(qū)鲁猩,則 Java 虛擬機(jī)會(huì)盡最大努力直接在此緩沖區(qū)上執(zhí)行本機(jī) I/O操作坎怪。也就是說(shuō)罢坝,在每次調(diào)用基礎(chǔ)操作系統(tǒng)的一個(gè)本機(jī) I/O 操作之前(或之后)廓握,虛擬機(jī)都會(huì)盡量避免將緩沖區(qū)的內(nèi)容復(fù)制到中間緩沖區(qū)中(或從中間緩沖區(qū)中復(fù)制內(nèi)容)。
- 直接字節(jié)緩沖區(qū)可以通過(guò)調(diào)用此類(lèi)的 allocateDirect() 工廠方法來(lái)創(chuàng)建嘁酿。此方法返回的緩沖區(qū)進(jìn)行分配和取消分配所需成本通常高于非直接緩沖區(qū)隙券。直接緩沖區(qū)的內(nèi)容可以駐留在常規(guī)的垃圾回收堆之外,因此闹司,它們對(duì)應(yīng)用程序的內(nèi)存需求量造成的影響可能并不明顯娱仔。所以,建議將直接緩沖區(qū)主要分配給那些易受基礎(chǔ)系統(tǒng)的本機(jī) I/O 操作影響的大型游桩、持久的緩沖區(qū)牲迫。一般情況下,最好僅在直接緩沖區(qū)能在程序性能方面帶來(lái)明顯好處時(shí)分配它們借卧。
- 直接字節(jié)緩沖區(qū)還可以通過(guò) FileChannel 的 map() 方法將文件區(qū)域直接映射到內(nèi)存中來(lái)創(chuàng)建盹憎。該方法返回MappedByteBuffer。Java 平臺(tái)的實(shí)現(xiàn)有助于通過(guò) JNI從本機(jī)代碼創(chuàng)建直接字節(jié)緩沖區(qū)铐刘。如果以上這些緩沖區(qū)中的某個(gè)緩沖區(qū)實(shí)例指的是不可訪(fǎng)問(wèn)的內(nèi)存區(qū)域陪每,則試圖訪(fǎng)問(wèn)該區(qū)域不會(huì)更改該緩沖區(qū)的內(nèi)容,并且將會(huì)在訪(fǎng)問(wèn)期間或稍后的某個(gè)時(shí)間導(dǎo)致拋出不確定的異常镰吵。
- 字節(jié)緩沖區(qū)是直接緩沖區(qū)還是非直接緩沖區(qū)可通過(guò)調(diào)用其 isDirect() 方法來(lái)確定檩禾。提供此方法是為了能夠在性能關(guān)鍵型代碼中執(zhí)行顯式緩沖區(qū)管理。
通道Channel
通道表示打開(kāi)到 IO 設(shè)備(例如:文件疤祭、套接字)的連接盼产。若需要使用 NIO 系統(tǒng),需要獲取用于連接 IO 設(shè)備的通道以及用于容納數(shù)據(jù)的緩沖區(qū)勺馆。然后操作緩沖區(qū)戏售,對(duì)數(shù)據(jù)進(jìn)行處理。Channel 負(fù)責(zé)傳輸谓传, Buffer 負(fù)責(zé)存儲(chǔ)蜈项。通道是由 java.nio.channels 包定義的。 Channel 表示 IO 源與目標(biāo)打開(kāi)的連接续挟。Channel 類(lèi)似于傳統(tǒng)的“流”紧卒。只不過(guò) Channel本身不能直接訪(fǎng)問(wèn)數(shù)據(jù), Channel 只能與Buffer 進(jìn)行交互诗祸。
Java 為 Channel 接口提供的最主要實(shí)現(xiàn)類(lèi)
- FileChannel:用于讀取跑芳、寫(xiě)入轴总、映射和操作文件的通道。
- DatagramChannel:通過(guò) UDP 讀寫(xiě)網(wǎng)絡(luò)中的數(shù)據(jù)通道博个。
- SocketChannel:通過(guò) TCP 讀寫(xiě)網(wǎng)絡(luò)中的數(shù)據(jù)怀樟。
- ServerSocketChannel:可以監(jiān)聽(tīng)新進(jìn)來(lái)的 TCP 連接,對(duì)每一個(gè)新進(jìn)來(lái)的連接都會(huì)創(chuàng)建一個(gè) SocketChannel盆佣。
獲取通道
獲取通道的一種方式是對(duì)支持通道的對(duì)象調(diào)用getChannel() 方法往堡。支持通道的類(lèi)如下:
- FileInputStream
- FileOutputStream
- RandomAccessFile
- DatagramSocket
- Socket
- ServerSocket
獲取通道的其他方式是使用 Files 類(lèi)的靜態(tài)方法 newByteChannel() 獲取字節(jié)通道」菜#或者通過(guò)通道的靜態(tài)方法 open() 打開(kāi)并返回指定通道虑灰。
通道的數(shù)據(jù)傳輸
//通道用于源節(jié)點(diǎn)與目標(biāo)節(jié)點(diǎn)之間的連接,在NIO中負(fù)責(zé)緩沖區(qū)中數(shù)據(jù)的傳輸痹兜。
//Channel本身不存儲(chǔ)數(shù)據(jù)穆咐,需要配合緩沖區(qū)進(jìn)行數(shù)據(jù)傳輸
/**
* 通道的主要實(shí)現(xiàn)類(lèi)
* java.nio.channels.Channel接口
* |--FileChannel
* |--SocketChannel
* |--ServerSocketChannel
* |--DatagramChannel
*
* 獲取通道
* 1.Java針對(duì)支持通道的類(lèi)提供了getChannel()方法
* 本地IO:
* FileInputStream/FileOutputStream
* RandomAccessFile
*
* 網(wǎng)絡(luò)IO:
* Socket
* ServerSocket
* DatagramSocket
*
* 2.在JDK1.7中NIO.2針對(duì)各個(gè)通道提供了靜態(tài)方法open()
* 3.在JDK1.7中NIO.2的Files工具類(lèi)的newByteChannel()
*/
public class TestChannel {
//利用通道完成文件的復(fù)制(非直接緩沖區(qū))
@Test
public void test1() {
//26088
//6479
//6587
//6464
long start = System.currentTimeMillis();
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
fileInputStream = new FileInputStream("E:\\BaiduYunDownload\\juc.zip");
fileOutputStream = new FileOutputStream("F:\\juc_copy2.zip");
//獲取通道
inChannel = fileInputStream.getChannel();
outChannel = fileOutputStream.getChannel();
//分配指定大小的緩沖區(qū)
ByteBuffer buffer = ByteBuffer.allocate(1024);
//將通道中的數(shù)據(jù)存入緩沖區(qū)
while (inChannel.read(buffer) != -1) {
//切換成讀取數(shù)據(jù)模式
buffer.flip();
//將緩沖區(qū)中的數(shù)據(jù)寫(xiě)入通道中
outChannel.write(buffer);
//清空緩沖區(qū)
buffer.clear();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//關(guān)閉通道 省略if判斷
outChannel.close();
inChannel.close();
//關(guān)閉流
fileOutputStream.close();
fileInputStream.close();
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
@Test
public void test2() throws IOException {
//1190
//5144
//5932
//1316
//1126
//998
//1242
long start = System.currentTimeMillis();
//使用直接緩沖區(qū)完成文件的復(fù)制(內(nèi)存映射文件)
//只有ByteBuffer支持直接緩沖區(qū)
FileChannel inChannel = FileChannel.open(Paths.get("E:\\BaiduYunDownload\\", "juc.zip"), StandardOpenOption.READ);
//StandardOpenOption.CREATE_NEW若存在則報(bào)錯(cuò)
//StandardOpenOption.CREATE若存在則覆蓋
FileChannel outChannel = FileChannel.open(Paths.get("F:/", "juc-3.zip"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
//內(nèi)存映射文件。緩沖區(qū)在物理內(nèi)存中字旭。
MappedByteBuffer inMappedByteBuffer = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
MappedByteBuffer outMappedByteBuffer = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size());
//直接對(duì)緩沖區(qū)進(jìn)行數(shù)據(jù)讀寫(xiě)操作
byte[] dst = new byte[inMappedByteBuffer.limit()];
inMappedByteBuffer.get(dst);
outMappedByteBuffer.put(dst);
inChannel.close();
outChannel.close();
long end = System.currentTimeMillis();
System.out.println(end - start);
}
@Test
public void test3() throws IOException {
//將數(shù)據(jù)從源通道傳輸?shù)狡渌?Channel 中
//729
//684
//601
//706
//625
long start = System.currentTimeMillis();
FileChannel inChannel = FileChannel.open(Paths.get("E:\\BaiduYunDownload\\", "juc.zip"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("F:/", "juc-4.zip"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
//通道之間的數(shù)據(jù)傳輸
//inChannel.transferTo(0, inChannel.size(), outChannel);
outChannel.transferFrom(inChannel, 0, inChannel.size());
inChannel.close();
outChannel.close();
long end = System.currentTimeMillis();
System.out.println(end - start);
}
@Test
public void test4() throws IOException {
RandomAccessFile randomAccessFile1 = new RandomAccessFile("E:/a.txt", "rw");
//獲取通道
FileChannel fileChannel1 = randomAccessFile1.getChannel();
//分配指定大小的緩沖區(qū)
ByteBuffer buffer1 = ByteBuffer.allocate(100);
ByteBuffer buffer2 = ByteBuffer.allocate(1024);
//分散讀取,從 Channel 中讀取的數(shù)據(jù)“分散” 到多個(gè) Buffer 中
ByteBuffer[] buffers = {buffer1, buffer2};
fileChannel1.read(buffers);
for (int i = 0; i < buffers.length; i++) {
buffers[i].flip();
}
System.out.println(new String(buffers[0].array(), 0, buffers[0].limit()));
System.out.println("-------------------");
System.out.println(new String(buffers[1].array(), 0, buffers[1].limit()));
//聚集寫(xiě)入,將多個(gè) Buffer 中的數(shù)據(jù)“聚集”到 Channel
RandomAccessFile randomAccessFile2 = new RandomAccessFile("E:/b.txt", "rw");
FileChannel fileChannel2 = randomAccessFile2.getChannel();
fileChannel2.write(buffers);
}
@Test
public void test5() {
/**
* 編碼:字符串->字節(jié)數(shù)組
* 解碼:字節(jié)數(shù)組->字符串
*/
//獲取所有支持的字符集
SortedMap<String, Charset> availableCharsets = Charset.availableCharsets();
Set<Entry<String, Charset>> set = availableCharsets.entrySet();
for (Entry<String, Charset> entry: set) {
System.out.println(entry.getKey() + "--" + entry.getValue());
}
}
@Test
public void test6() throws CharacterCodingException {
Charset charset = Charset.forName("GBK");
//編碼器
CharsetEncoder charsetEncoder = charset.newEncoder();
//解碼器
CharsetDecoder charsetDecoder = charset.newDecoder();
CharBuffer charBuffer = CharBuffer.allocate(1024);
charBuffer.put("你好");
charBuffer.flip();
//編碼
ByteBuffer byteBuffer = charsetEncoder.encode(charBuffer);
for (int i = 0; i < 4; i++) {
//字節(jié)數(shù)組
System.out.println(byteBuffer.get());
}
//切換到讀模式
byteBuffer.flip();
//解碼
CharBuffer charBuffer2 = charsetDecoder.decode(byteBuffer);
System.out.println(charBuffer2.toString());
}
}