1.概述java
Java NIO(New IO) 是從Java 1.4版本開始引入的一個新的IO API,能夠替代標準的Java IO API。
NIO與原來的IO有一樣的做用和目的,可是使用的方式徹底不一樣, NIO支持面向緩衝區的、基於通道的IO操做。 NIO將以更加高效的方式進行文件的讀寫操做。
數組
Java NIO系統的核心在於:服務器
通道(Channel)和緩衝區(Buffer)。網絡
通道表示打開到 IO 設備(例如:文件、套接字)的鏈接。併發
若須要使用 NIO 系統,須要獲取用於鏈接 IO 設備的通道以及用於容納數據的緩衝區。而後操做緩衝區,對數據進行處理。
app
簡而言之, Channel 負責傳輸, Buffer 負責存儲
dom
Buffer 中的重要概念:
容量 (capacity) : 表示 Buffer 最大數據容量,緩衝區容量不能爲負,而且創
建後不能更改。
限制 (limit): 第一個不該該讀取或寫入的數據的索引,即位於 limit 後的數據
不可讀寫。緩衝區的限制不能爲負,而且不能大於其容量。
位置 (position): 下一個要讀取或寫入的數據的索引。緩衝區的位置不能爲
負,而且不能大於其限制
標記 (mark)與重置 (reset): 標記是一個索引,經過 Buffer 中的 mark() 方法
指定 Buffer 中一個特定的 position,以後能夠經過調用 reset() 方法恢復到這
個 position.
標記、 位置、 限制、 容量遵照如下不變式: 0 <= mark <= position <= limit <= capacity
socket
2.NIO與IO的區別ide
NIO工具
傳統的IO
3.緩衝區(buffer)
package com.zy.nio; import org.junit.Test; import java.nio.ByteBuffer; /* * 1、緩衝區(Buffer):在 Java NIO 中負責數據的存取。緩衝區就是數組。用於存儲不一樣數據類型的數據 * * 根據數據類型不一樣(boolean 除外),提供了相應類型的緩衝區: * ByteBuffer * CharBuffer * ShortBuffer * IntBuffer * LongBuffer * FloatBuffer * DoubleBuffer * * 上述緩衝區的管理方式幾乎一致,經過 allocate() 獲取緩衝區 * * 2、緩衝區存取數據的兩個核心方法: * put() : 存入數據到緩衝區中 * get() : 獲取緩衝區中的數據 * * 3、緩衝區中的四個核心屬性: * capacity : 容量,表示緩衝區中最大存儲數據的容量。一旦聲明不能改變。 * limit : 界限,表示緩衝區中能夠操做數據的大小。(limit 後數據不能進行讀寫) * position : 位置,表示緩衝區中正在操做數據的位置。 * * mark : 標記,表示記錄當前 position 的位置。能夠經過 reset() 恢復到 mark 的位置 * * 0 <= mark <= position <= limit <= capacity * * 4、直接緩衝區與非直接緩衝區: * 非直接緩衝區:經過 allocate() 方法分配緩衝區,將緩衝區創建在 JVM 的內存中 * 直接緩衝區:經過 allocateDirect() 方法分配直接緩衝區,將緩衝區創建在物理內存中。能夠提升效率 */ public class NioBufferDemo01 { @Test public void fn03(){ // 間接緩衝區 ByteBuffer buffer = ByteBuffer.allocate(1024); // 直接緩衝區 ByteBuffer diretBuffer = ByteBuffer.allocateDirect(1024); System.out.println(buffer.isDirect()); System.out.println(diretBuffer.isDirect()); } @Test public void fn02(){ String str = "qwertyuiop"; ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.put(str.getBytes()); buffer.flip(); byte[] b = new byte[buffer.limit()]; buffer.get(b, 0, 2); System.out.println(new String(b, 0, 2)); System.out.println(buffer.position()); // mark:標記 System.out.println("-----------------mark()----------------"); buffer.mark(); buffer.get(b, 2, 2); System.out.println(new String(b, 2, 2)); System.out.println(buffer.position()); // reset:恢復到mark的位置 System.out.println("-----------------reset()----------------"); buffer.reset(); System.out.println(buffer.position()); //判斷緩衝區中是否還有剩餘數據 System.out.println("-----------------hasRemaining()----------------"); System.out.println("-----------------remaining()----------------"); if (buffer.hasRemaining()){ System.out.println(buffer.remaining()); } } @Test public void fn01(){ String string = "zxcvbnm"; //1. 分配一個指定大小的緩衝區 ByteBuffer buffer = ByteBuffer.allocate(1024); System.out.println("-----------------allocate()----------------"); System.out.println(buffer.position()); System.out.println(buffer.limit()); System.out.println(buffer.capacity()); //2. 利用 put() 存入數據到緩衝區中 buffer.put(string.getBytes()); System.out.println("-----------------put()----------------"); System.out.println(buffer.position()); System.out.println(buffer.limit()); System.out.println(buffer.capacity()); //3. 切換讀取數據模式 buffer.flip(); System.out.println("------------------flip()-------------------"); System.out.println(buffer.position()); System.out.println(buffer.limit()); System.out.println(buffer.capacity()); //4. 利用 get() 讀取緩衝區中的數據 byte[] b = new byte[buffer.limit()]; buffer.get(b); System.out.println(new String(b, 0, b.length)); System.out.println("------------------get()-------------------"); System.out.println(buffer.position()); System.out.println(buffer.limit()); System.out.println(buffer.capacity()); //5. rewind() : 可重複讀 buffer.rewind(); System.out.println("-----------------rewind()----------------"); System.out.println(buffer.position()); System.out.println(buffer.limit()); System.out.println(buffer.capacity()); //6. clear() : 清空緩衝區. 可是緩衝區中的數據依然存在,可是處於「被遺忘」狀態 buffer.clear(); System.out.println("------------------clear()------------------------"); System.out.println(buffer.position()); System.out.println(buffer.limit()); System.out.println(buffer.capacity()); System.out.println((char)buffer.get()); } }
4.通道
通道(Channel):由 java.nio.channels 包定義的。 Channel 表示 IO 源與目標打開的鏈接。
Channel 相似於傳統的「流」。只不過 Channel自己不能直接訪問數據, Channel 只能與Buffer 進行交互。
自己不存儲任何數據,須要配合緩衝區才能完成數據傳輸。
package com.zy.nio; import org.junit.Test; import java.io.*; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.SortedMap; /* * 1、通道(Channel):用於源節點與目標節點的鏈接。在 Java NIO 中負責緩衝區中數據的傳輸。Channel 自己不存儲數據,所以須要配合緩衝區進行傳輸。 * * 2、通道的主要實現類 * java.nio.channels.Channel 接口: * |--FileChannel 用於讀取、寫入、映射和操做文件的通道。 * |--SocketChannel 經過 TCP 讀寫網絡中的數據 * |--ServerSocketChannel 能夠監聽新進來的 TCP 鏈接,對每個新進來的鏈接都會建立一個 SocketChannel * |--DatagramChannel 經過 UDP 讀寫網絡中的數據通道 * * 3、獲取通道有三種方式 * 1. Java 針對支持通道的類提供了 getChannel() 方法 * 本地 IO: * FileInputStream/FileOutputStream * RandomAccessFile * * 網絡IO: * Socket * ServerSocket * DatagramSocket * * 2. 在 JDK 1.7 中的 NIO.2 針對各個通道提供了靜態方法 open() * 3. 在 JDK 1.7 中的 NIO.2 的 Files 工具類的 newByteChannel() * * 4、通道之間的數據傳輸 * transferFrom() * transferTo() * * 5、分散(Scatter)與彙集(Gather) * 分散讀取(Scattering Reads):將通道中的數據分散到多個緩衝區中 * 彙集寫入(Gathering Writes):將多個緩衝區中的數據彙集到通道中 * * 6、字符集:Charset * 編碼:字符串 -> 字節數組 * 解碼:字節數組 -> 字符串 * */ public class NioChannelDemo01 { // 6.指定字符集的編碼與解碼 @Test public void fn06() throws Exception { Charset charset = Charset.forName("utf-8"); // 獲取編碼器 CharsetEncoder encoder = charset.newEncoder(); // 獲取解碼器 CharsetDecoder decoder = charset.newDecoder(); CharBuffer cBuffer = CharBuffer.allocate(1024); cBuffer.put("好好學習,每天向上"); cBuffer.flip(); // 編碼 ByteBuffer bBuffer = encoder.encode(cBuffer); // 解碼 bBuffer.flip(); CharBuffer charBuffer = decoder.decode(bBuffer); System.out.println(charBuffer); } // 5.遍歷全部支持的字符集 @Test public void fn05(){ SortedMap<String, Charset> charsets = Charset.availableCharsets(); charsets.forEach((k,v)->{ System.out.println("item:"+k+"===============value:"+v); }); } // 4.分散讀取與彙集寫入 @Test public void fn04() throws Exception{ RandomAccessFile raf = new RandomAccessFile("E:/idea.txt", "rw"); // 獲取通道 FileChannel channel = raf.getChannel(); // 分配指定的緩衝區的大小 ByteBuffer buffer = ByteBuffer.allocate(100); ByteBuffer buffer1 = ByteBuffer.allocate(1024); // 分散讀取 ByteBuffer[] buffers = {buffer, buffer1}; channel.read(buffers); for (ByteBuffer bf : buffers){ bf.flip(); } System.out.println("==================分散讀取開始===================="); System.out.println(new String(buffers[0].array(), 0, buffers[0].limit())); System.out.println(new String(buffers[1].array(), 0, buffers[1].limit())); System.out.println("==================分散讀取結束===================="); // 彙集寫入 RandomAccessFile raf2 = new RandomAccessFile("E:/idea01.txt", "rw"); FileChannel channel1 = raf2.getChannel(); channel1.write(buffers); } // 3.使用直接緩衝區完成文件的複製(較爲簡便的方式) @Test public void fn03(){ FileChannel in = null; FileChannel out = null; try { in = FileChannel.open(Paths.get("E:/1.png"), StandardOpenOption.READ); out = FileChannel.open(Paths.get("E:/4.png"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); // 方法一: in.transferTo(0, in.size(), out); // 方法二: out.transferFrom(in, 0, in.size()); } catch (IOException e) { e.printStackTrace(); } finally { try { out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } } } // 2.使用直接緩衝區完成文件的複製(內存映射文件)(較爲複雜的方式,少用) /*建議將直接緩衝區主要分配給那些易受基礎系統的本機 I/O 操做影響的大型、持久的緩衝區。 通常狀況下,最好僅在直接緩衝區能在程序性能方面帶來明顯好處時分配它們*/ @Test public void fn02(){ FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = FileChannel.open(Paths.get("E:/1.png"), StandardOpenOption.READ); outChannel = FileChannel.open(Paths.get("E:/3.png"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE); // 內存映射文件,只支持byteBuffer MappedByteBuffer inMapBuffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size()); MappedByteBuffer outMapBuffer = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size()); //直接對緩衝區進行數據的讀寫操做 byte[] b = new byte[inMapBuffer.limit()]; inMapBuffer.get(b); outMapBuffer.put(b); } catch (IOException e) { e.printStackTrace(); } finally { try { inChannel.close(); outChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } // 1.利用通道完成文件的複製(非直接緩衝區) @Test public void fn01(){ FileInputStream is = null; FileOutputStream os = null; FileChannel inChannel = null; FileChannel outChannel = null; try { is = new FileInputStream("E:/1.png"); os = new FileOutputStream("E:/2.png"); // 獲取通道 inChannel = is.getChannel(); outChannel = os.getChannel(); // 分配指定大小的緩衝區 ByteBuffer buffer = ByteBuffer.allocate(1024); // 將通道中的數據存入緩衝區中 while (inChannel.read(buffer) != -1){ // 切換讀取數據的模式 buffer.flip(); // 將緩衝區的數據寫入通道中 outChannel.write(buffer); // 清空緩衝區 buffer.clear(); } } catch (IOException e) { e.printStackTrace(); } finally { try { outChannel.close(); inChannel.close(); os.close(); is.close(); } catch (IOException e) { e.printStackTrace(); } } } }
5.Blocking NIO
package com.zy.nio; import org.junit.Test; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; /* * 1、使用 NIO 完成網絡通訊的三個核心: * * 1. 通道(Channel):負責鏈接 * * java.nio.channels.Channel 接口: * |--SelectableChannel * |--SocketChannel * |--ServerSocketChannel * |--DatagramChannel * * |--Pipe.SinkChannel * |--Pipe.SourceChannel * * 2. 緩衝區(Buffer):負責數據的存取 * * 3. 選擇器(Selector):是 SelectableChannel 的多路複用器。用於監控 SelectableChannel 的 IO 情況 * */ public class BlockNioDemo01 { // 客戶端 @Test public void client() throws IOException { // 1.獲取通道 SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8888)); FileChannel inChannel = FileChannel.open(Paths.get("E:/1.png"), StandardOpenOption.READ); // 2.分配指定的緩衝區的大小 ByteBuffer buffer = ByteBuffer.allocate(1024); // 3.讀取本地文件,併發送到服務端 while (inChannel.read(buffer) != -1){ buffer.flip(); socketChannel.write(buffer); buffer.clear(); } // 4.關閉通道 inChannel.close(); socketChannel.close(); } // 服務端 @Test public void server() throws IOException { // 1.獲取通道 ServerSocketChannel channel = ServerSocketChannel.open(); FileChannel outChannel = FileChannel.open(Paths.get("E:/5.png"), StandardOpenOption.WRITE, StandardOpenOption.CREATE); // 2.綁定鏈接 channel.bind(new InetSocketAddress(8888)); // 3.獲取客戶端鏈接的通道 SocketChannel clientChannel = channel.accept(); // 4.分配指定的緩衝區的大小 ByteBuffer buffer = ByteBuffer.allocate(1024); // 5.接收客戶端的數據並保存到本地 while (clientChannel.read(buffer) != -1){ buffer.flip(); outChannel.write(buffer); buffer.clear(); } // 6.關閉資源 clientChannel.close(); outChannel.close(); channel.close(); } }
package com.zy.nio; import org.junit.Test; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; /** * * 阻塞式NIO2 */ public class BlockNio2Demo01 { // 客戶端 @Test public void client() throws IOException { // 1.獲取通道 SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9999)); FileChannel fileChannel = FileChannel.open(Paths.get("E:/1.png"), StandardOpenOption.READ); // 2.分配指定的緩衝區的大小 ByteBuffer buffer = ByteBuffer.allocate(1024); // 3.讀取本地文件,併發送到服務端 while (fileChannel.read(buffer) != -1){ buffer.flip(); socketChannel.write(buffer); buffer.clear(); } socketChannel.shutdownOutput(); // 4.接收服務端的反饋 int len = 0; while ((len = socketChannel.read(buffer)) != -1){ buffer.flip(); System.out.println(new String(buffer.array(), 0, len)); buffer.clear(); } // 5.關閉資源 fileChannel.close(); socketChannel.close(); } // 服務端 @Test public void server() throws IOException { // 1.獲取通道 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); FileChannel fileChannel = FileChannel.open(Paths.get("E:/6.png"), StandardOpenOption.WRITE, StandardOpenOption.CREATE); // 2.綁定鏈接 serverSocketChannel.bind(new InetSocketAddress(9999)); // 3.獲取客戶端鏈接的通道 SocketChannel socketChannel = serverSocketChannel.accept(); // 4.分配指定緩衝區的大小 ByteBuffer buffer = ByteBuffer.allocate(1024); // 5.將客戶端的資源保存到本地 while (socketChannel.read(buffer) != -1){ buffer.flip(); fileChannel.write(buffer); buffer.clear(); } // 6.發送反饋給客戶端 buffer.put("服務端數據接收成功".getBytes()); buffer.flip(); socketChannel.write(buffer); // 7.關閉資源 socketChannel.close(); fileChannel.close(); serverSocketChannel.close(); } }
6.Non-Blocking NIO
TCP
package com.zy.nio; import org.junit.Test; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.time.LocalDateTime; import java.util.Iterator; import java.util.Scanner; /* * 1、使用 NIO 完成網絡通訊的三個核心: * * 1. 通道(Channel):負責鏈接 * * java.nio.channels.Channel 接口: * |--SelectableChannel * |--SocketChannel * |--ServerSocketChannel * |--DatagramChannel * * |--Pipe.SinkChannel * |--Pipe.SourceChannel * * 2. 緩衝區(Buffer):負責數據的存取 * * 3. 選擇器(Selector):是 SelectableChannel 的多路複用器。用於監控 SelectableChannel 的 IO 情況 * * 非阻塞式NIO */ public class NonBlockNioDemo01 { // 客戶端 @Test public void client() throws IOException { // 1.獲取通道 SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9090)); // 2.切換爲非阻塞模式 socketChannel.configureBlocking(false); // 3.分配指定大小的緩衝區 ByteBuffer buffer = ByteBuffer.allocate(1024); // 4.發送消息到服務器 Scanner scanner = new Scanner(System.in); while (scanner.hasNext()){ String str = scanner.next(); buffer.put((LocalDateTime.now().toString()+"\n"+str).getBytes()); buffer.flip(); socketChannel.write(buffer); buffer.clear(); } // 5.關閉通道 socketChannel.close(); } // 服務端 @Test public void server() throws IOException { // 1.獲取通道 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); // 2.切換爲非阻塞模式 serverSocketChannel.configureBlocking(false); // 3.綁定鏈接 serverSocketChannel.bind(new InetSocketAddress(9090)); // 4.獲取選擇器 Selector selector = Selector.open(); // 5.將通道註冊到選擇器上,指定監聽事件 serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); // 6.輪詢式的獲取選擇器上準備就緒的事件 while (selector.select() > 0){ // 7.獲取當前選擇器中全部註冊的選擇鍵(已就緒的監聽事件) Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator(); // 8.迭代獲取準備就緒的事件 while (keyIterator.hasNext()){ SelectionKey next = keyIterator.next(); // 9.判斷具體是什麼事件準備就緒 if (next.isAcceptable()){ // 10.若接收就緒,則獲取客戶端鏈接 SocketChannel socketChannel = serverSocketChannel.accept(); // 11.切換爲非阻塞模式 socketChannel.configureBlocking(false); // 12.將該通道註冊到選擇器上 socketChannel.register(selector, SelectionKey.OP_READ); } else if (next.isReadable()){ // 獲取讀就緒通道 SocketChannel channel = (SocketChannel) next.channel(); // 讀取數據 ByteBuffer buffer = ByteBuffer.allocate(1024); int len = 0; while ((len = channel.read(buffer)) > 0){ buffer.flip(); System.out.println(new String(buffer.array(), 0, len)); buffer.clear(); } } // 取消選擇鍵 keyIterator.remove(); } } } }
UDP
package com.zy.nio; import org.junit.Test; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.time.LocalDateTime; import java.util.Iterator; import java.util.Scanner; /** * UDP-NIO */ public class NonBlockNioDemo02 { // 客戶端 @Test public void client() throws IOException { // 1.獲取通道 DatagramChannel datagramChannel = DatagramChannel.open(); // 2.切換爲非阻塞模式 datagramChannel.configureBlocking(false); // 3.分配指定的緩衝區大小 ByteBuffer buffer = ByteBuffer.allocate(1024); // 4.發送消息到服務器 Scanner scanner = new Scanner(System.in); while (scanner.hasNext()){ String next = scanner.next(); buffer.put((LocalDateTime.now().toString()+"\n"+next).getBytes()); buffer.flip(); datagramChannel.send(buffer, new InetSocketAddress("127.0.0.1",9090)); buffer.clear(); } // 5.關閉資源 datagramChannel.close(); } // 服務端 @Test public void server() throws IOException { // 1.獲取通道 DatagramChannel datagramChannel = DatagramChannel.open(); // 2.切換爲nio狀態 datagramChannel.configureBlocking(false); // 3.綁定鏈接 datagramChannel.bind(new InetSocketAddress(9090)); // 4.得到選擇器 Selector selector = Selector.open(); // 5.將通道註冊到選擇器上,並綁定監聽事件 datagramChannel.register(selector, SelectionKey.OP_READ); // 6.經過輪詢方式獲取選擇器上準備就緒的事件 while (selector.select() > 0){ Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()){ SelectionKey next = it.next(); if (next.isReadable()){ ByteBuffer buffer = ByteBuffer.allocate(1024); datagramChannel.receive(buffer); buffer.flip(); System.out.println(new String(buffer.array(), 0, buffer.limit())); buffer.clear(); } } it.remove(); } } }
7.管道 (Pipe)
Java NIO 管道是2個線程之間的單向數據鏈接。Pipe有一個source通道和一個sink通道。數據會被寫到sink通道,從source通道讀取。
package com.zy.nio; import org.junit.Test; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Pipe; public class PipeNioDemo01 { @Test public void fn() throws IOException { // 1.獲取管道 Pipe pipe = Pipe.open(); // 2.將緩衝區中的數據寫入管道 ByteBuffer buffer = ByteBuffer.allocate(1024); Pipe.SinkChannel sinkChannel = pipe.sink(); buffer.put("經過單向管道發送數據".getBytes()); buffer.flip(); sinkChannel.write(buffer); // 3.讀取管道緩衝區中的數據 Pipe.SourceChannel sourceChannel = pipe.source(); buffer.flip(); int len = sourceChannel.read(buffer); System.out.println(new String(buffer.array(), 0, len)); sourceChannel.close(); sinkChannel.close(); } }
8.NIO2
8.1Path 與 Paths
java.nio.file.Path 接口表明一個平臺無關的平臺路徑,描述了目錄結構中文件的位置。
Paths 提供的 get() 方法用來獲取 Path 對象:
Path get(String first, String … more) : 用於將多個字符串串連成路徑。
Path 經常使用方法:
boolean endsWith(String path) : 判斷是否以 path 路徑結束
boolean startsWith(String path) : 判斷是否以 path 路徑開始
boolean isAbsolute() : 判斷是不是絕對路徑
Path getFileName() : 返回與調用 Path 對象關聯的文件名
Path getName(int idx) : 返回的指定索引位置 idx 的路徑名稱
int getNameCount() : 返回Path 根目錄後面元素的數量
Path getParent() :返回Path對象包含整個路徑,不包含 Path 對象指定的文件路徑
Path getRoot() :返回調用 Path 對象的根路徑
Path resolve(Path p) :將相對路徑解析爲絕對路徑
Path toAbsolutePath() : 做爲絕對路徑返回調用 Path 對象
String toString() : 返回調用 Path 對象的字符串表示形式
8.2Files 類
java.nio.file.Files 用於操做文件或目錄的工具類。
Files經常使用方法:
Path copy(Path src, Path dest, CopyOption … how) : 文件的複製
Path createDirectory(Path path, FileAttribute<?> … attr) : 建立一個目錄
Path createFile(Path path, FileAttribute<?> … arr) : 建立一個文件
void delete(Path path) : 刪除一個文件
Path move(Path src, Path dest, CopyOption…how) : 將 src 移動到 dest 位置
long size(Path path) : 返回 path 指定文件的大小
Files經常使用方法:用於判斷
boolean exists(Path path, LinkOption … opts) : 判斷文件是否存在
boolean isDirectory(Path path, LinkOption … opts) : 判斷是不是目錄
boolean isExecutable(Path path) : 判斷是不是可執行文件
boolean isHidden(Path path) : 判斷是不是隱藏文件
boolean isReadable(Path path) : 判斷文件是否可讀
boolean isWritable(Path path) : 判斷文件是否可寫
boolean notExists(Path path, LinkOption … opts) : 判斷文件是否不存在
public static <A extends BasicFileAttributes> A readAttributes(Path path,Class<A> type,LinkOption...options) : 獲取與 path 指定的文件相關聯的屬性。
Files經常使用方法: 用於操做內容
SeekableByteChannel newByteChannel(Path path, OpenOption…how) : 獲取與指定文件的鏈接,how 指定打開方式。
DirectoryStream newDirectoryStream(Path path) : 打開 path 指定的目錄
InputStream newInputStream(Path path, OpenOption…how):獲取 InputStream 對象
OutputStream newOutputStream(Path path, OpenOption…how) : 獲取 OutputStream 對象
8.3自動資源管理
Java 7 增長了一個新特性,該特性提供了另一種管理資源的方式,這種方式能自動關閉文件。
這個特性有時被稱爲自動資源管理(Automatic Resource Management, ARM), 該特性以 try 語句的擴展版爲基礎。
自動資源管理主要用於,當再也不須要文件(或其餘資源)時,能夠防止無心中忘記釋放它們。