原文連接:https://blog.csdn.net/qq877728715/article/details/104499687/
文章目錄
Java7新增文件IO類
Java7中文件IO發生了很大的變化,專門引入了不少新的類:java
java.nio.file.DirectoryStream;
java.nio.file.FileSystem;
java.nio.file.FileSystems;
java.nio.file.Files;
java.nio.file.Path;
java.nio.file.Paths;
java.nio.file.attribute.FileAttribute;
java.nio.file.attribute.PosixFilePermission;
java.nio.file.attribute.PosixFilePermissions;
安全
在java中文件或是目錄習慣用java.io.File
對象來表示,可是File類有不少缺陷app
-
它的不少方法不能拋出異常工具
-
它的delete方法常常莫名其妙的失敗等,舊的File類常常是程序失敗的根源。測試
-
所以在Java7中有了更好的替代:
java.nio.file.Path
及java.nio.file.Files
。ui-
Path接口的名字很是恰當,就是表示路徑的,API中講
Path對象能夠是一個文件,一個目錄,或是一個符號連接,也能夠是一個根目錄。
用法很簡單。建立Path並不會建立物理文件或是目錄,path實例常常引用並不存在的物理對象,要真正建立文件或是目錄,須要用到Files類
。編碼 -
Files類是一個很是強大的類,它提供了處理文件和目錄以及讀取文件和寫入文件的靜態方法。 能夠用它
建立和刪除路徑。複製文件。檢查路徑是否存在等。
此外。Files還擁有建立流對象
的方法。spa
-
一.Paths
Paths類僅由靜態方法組成,經過轉換路徑字符串返回Path或URI
。.net
- 由於就兩個方法用來生成Path對象,以供Path和Files使用;而Path也常常由Paths來生成,又或者File類有一個toPath();方法能夠使用
1.建立Paths
二.Path
Path就是取代File的,用於來表示文件路徑和文件。能夠有多種方法來構造一個Path對象來表示一個文件路徑,或者一個文件:
- 該接口的實現是不可變且安全的,可供多個並行線程使用。
線程
1.建立Path
1.1.建立Path的三種方式
建立Path的三種方式
Path path=FileSystems.getDefault().getPath("d:/users/日記5.txt"); //並無實際建立路徑,而是一個指向d:/users/日記5.txt路徑的引用
Path path=Paths.get(「d:/users/日記5.txt」); //Paths類提供了這個快捷方法,直接經過它的靜態get方法建立path
Path path= = new File(「d:/users/日記5.txt」).toPath();
2.Path經常使用方法
Path接口沒什麼判斷方法,其實更多的判斷和操做都在Files工具類裏面
boolean isAbsolute() //告訴這條路是不是絕對的 boolean endsWith(Path other) //測試此路徑是否以給定的路徑結束 boolean endsWith(String other) //測試此路徑是否以給定字符串結束,如"c:/a/banana/cat"能夠以"/banana/cat"結尾,但不能以"t"結尾 boolean startsWith(Path other) //測試此路徑是否以給定的路徑開始。 boolean startsWith(String other) //測試此路徑是否以給定字符串開始,跟上面同樣規律
Path getFileName()
//將此路徑表示的文件或目錄的名稱返回爲 Path對象,文件名或文件夾名,不含路徑
Path getName(int index)
//返回此路徑的名稱元素做爲 Path對象。目錄中最靠近root的爲0,最遠的爲(count-1),count由下面的方法得到
int getNameCount()
//返回路徑中的名稱元素的數量。0則只有root
Path getParent()
//返回 父路徑,若是此路徑沒有父返回null,如/a/b/c返回/a/b,配合下面的方法消除".「或」…"
Path normalize()
//返回一個路徑,該路徑是冗餘名稱元素的消除。如消除掉"."、"…"
Path getRoot()
//返回此路徑的根組分做爲 Path對象,或 null若是該路徑不具備根組件。如返回"c:/"
Path relativize(Path other)
//構造此路徑和給定路徑之間的相對路徑。有點難理解,p1-「Topic.txt」,p2-「Demo.txt」,p3-"/Java/JavaFX/Topic.txt",p4-"/Java/2011";;那麼p1和p2的結果是"…/Demo.txt";;p2和p1的結果是"…/Topic.txt";;p3和p4的結果是"…/…/2011";;p4和p3的結果是"…/JavaFX/Topic.txt"
Path resolve(String other)
//將給定的路徑字符串轉換爲 Path。如"c:/a/b"和字符串"c.txt"的結果是"c:/a/b/c.txt";更像是拼接
Path resolveSibling(String other)
//將給定的路徑字符串轉換爲 Path。如"c:/a/b.txt"和字符串"c.txt"的結果是"c:/a/c.txt";更像是替換
Path subpath(int beginIndex, int endIndex)
//返回一個相對的 Path ,它是該路徑的名稱元素的子序列,如"d:/a/b/c.txt"參數爲(1,3)返回一個"b/c.txt"
Path toAbsolutePath()
//返回表示此路徑的絕對路徑的 Path對象。包括盤符和文件名或文件夾名
Iterator<Path> iterator()
//返回此路徑的名稱元素的迭代器。「c:/a/b/c.txt"的迭代器能夠next出如下"a」「b」「c.txt」
File toFile()
//返回表示此路徑的File對象
三.Files
Files類只包含對文件,目錄或其餘類型文件進行操做的靜態方法。主要和Path接口的對象進行配合使用
1.判斷方法:
2.刪除方法
- 4
3.複製方法
4.移動和重命名方法
5.建立文件和文件夾方法
6.文件屬性方法
static <V extends FileAttributeView> V getFileAttributeView(Path path, 類<V> type, LinkOption... options) //返回給定類型的文件屬性視圖。指定六個視圖其中一種,上面一開始有點到。拿到的xxxAttributeView會有一個跟下面同樣名字的readAttributes方法來獲得一個xxxAttributes真正的獲取操做就全是在這個xxxAttributes類的對象裏get啦 static <A extends BasicFileAttributes> A readAttributes(Path path, 類<A> type, LinkOption... options) //讀取文件的屬性做爲批量操做。指定一個xxxAttributes,獲得一個實例,經過裏面的方法獲得時間等基本屬性
static Object getAttribute(Path path, String attribute, LinkOption... options)
//讀取文件屬性的值。這個 String attributes 參數的語法固定是以 view-name:comma-separated-attributes 的形式;view-name指定視圖名如basic,posix,acl等,不寫默認爲basic;有寫默認要加":";能夠用"basic:「或」"讀取全部,又或者用"basic:size,lastModifiedTime"讀取大小和修改時間。具體還有那些屬性能夠看具體指定的類,好比basic視圖就看BasicFileAttributes這個接口都有哪些方法,能夠讀取哪些文件屬性。同理,下面的 String attributes 同樣是這個理
static Map<String,Object> readAttributes(Path path, String attributes, LinkOption... options)
//讀取一組文件屬性做爲批量操做。
static Path setAttribute(Path path, String attribute, Object value, LinkOption... options)
//設置文件屬性的值。
/* 下面這些也是獲取屬性的方法,不過還沒研究到是怎麼用的 */
static FileTime getLastModifiedTime(Path path, LinkOption... options)
//返回文件的上次修改時間。
static UserPrincipal getOwner(Path path, LinkOption... options)
//返回文件的全部者。
static Set<PosixFilePermission> getPosixFilePermissions(Path path, LinkOption... options)
//返回文件的POSIX文件權限。
static Path setLastModifiedTime(Path path, FileTime time)
//更新文件上次修改的時間屬性。
static Path setOwner(Path path, UserPrincipal owner)
//更新文件全部者。
static Path setPosixFilePermissions(Path path, Set<PosixFilePermission> perms)
//設置文件的POSIX權限。
static long size(Path path)
//返回文件的大小(以字節爲單位)。
7.讀取、編輯文件內容方法
以上方法適用於處理中等長度的文本文
件,若是要處理的文件長度比較大,或者是二進制文件,那麼仍是應該使用流
8.遍歷文件列表方法
- newDirectoryStream只是遍歷當前Path的子目錄列表,或者寫一個方法裏面遞歸調用實現遍歷到底;
- walk則是能夠經過maxDepth參數來決定遍歷的深度,後面的FileVisitOption參數無關緊要;
- list相似於newDirectoryStream,區別是walk和newDirectoryStream是遞歸的,list是非遞歸的
static DirectoryStream<Path> newDirectoryStream(Path dir) //打開一個目錄,返回一個DirectoryStream以遍歷目錄中的全部條目。最好用 try-with-resources 構造,能夠自動關閉資源。返回的 DirectoryStream<Path> 其實能夠直接使用 Iterator或者for循環 遍歷每個 dir 下面的文件或目錄 static DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter) //上面方法的重載,經過實現參數二(有一個 boolean accept(Path p) 方法來判斷文件是否符合須要)來達到過濾的目的。如accept方法中寫"return (Files.size(p) > 8192L);"來匹配大於8k的文件 static DirectoryStream<Path> newDirectoryStream(Path dir, String glob) //上面方法的重載,能夠經過參數二做爲過濾匹配出對應的文件。如 newDirectoryStream(dir, "*.java") 用於遍歷目錄裏全部java後綴的文件
static Stream<Path> walk(Path start, FileVisitOption... options)
//深度優先遍歷。返回一個 Stream ,它經過 Path根據給定的起始文件的文件樹懶惰地填充 Path 。
static Stream<Path> walk(Path start, int maxDepth, FileVisitOption... options)
//深度優先遍歷。返回一個 Stream ,它是經過走根據給定的起始文件的文件樹懶惰地填充 Path 。
static Stream<Path> list(Path dir)
//返回一個懶惰的填充 Stream ,其元素是 Stream中的條目。返回的 Stream 裏封裝了一個 DirectoryStream 用於遍歷。
四.Path和Files使用
import org.junit.Test; import java.io.*; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.PosixFilePermission; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Stream;
public class PathAndFilesTest {
/**
* 建立Path
*/
@Test
public void createPath() throws URISyntaxException, MalformedURLException {
//1.Paths
Path path = Paths.get(「F:/測試數據.csv」);
System.out.println(path.getFileName());
Path path1 = Paths.get(new URI(「file:///f:/測試數據.csv」));
<span class="token comment">//2.FileSystems</span> Path path2 <span class="token operator">=</span> FileSystems<span class="token punctuation">.</span><span class="token function">getDefault</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getPath</span><span class="token punctuation">(</span><span class="token string">"F:/測試數據.csv"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//3.File</span> Path path3 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">File</span><span class="token punctuation">(</span><span class="token string">"F:/測試數據.csv"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toPath</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token comment">/** * 建立一個空文件/文件夾 */</span> <span class="token annotation punctuation">@Test</span> <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> IOException <span class="token punctuation">{<!-- --></span> <span class="token comment">//文件夾</span> Path path <span class="token operator">=</span> Paths<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">"F:/hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>Files<span class="token punctuation">.</span><span class="token function">exists</span><span class="token punctuation">(</span>path<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span><span class="token comment">//若是不存在</span> Files<span class="token punctuation">.</span><span class="token function">createDirectory</span><span class="token punctuation">(</span>path<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//建立多個目錄</span> <span class="token comment">//Files.createDirectories(path);</span> <span class="token punctuation">}</span> <span class="token comment">//文件</span> Path path1 <span class="token operator">=</span> Paths<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">"F:/helloFile.txt"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>Files<span class="token punctuation">.</span><span class="token function">exists</span><span class="token punctuation">(</span>path1<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span><span class="token comment">//若是不存在</span> Files<span class="token punctuation">.</span><span class="token function">createFile</span><span class="token punctuation">(</span>path1<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> <span class="token comment">/** * 文件屬性 */</span> <span class="token annotation punctuation">@Test</span> <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">getFileProperties</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> IOException <span class="token punctuation">{<!-- --></span> Path path <span class="token operator">=</span> Paths<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">"F:/測試數據.csv"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>Files<span class="token punctuation">.</span><span class="token function">getLastModifiedTime</span><span class="token punctuation">(</span>path<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//最後修改時間:2019-05-22T02:52:45.625094Z</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>Files<span class="token punctuation">.</span><span class="token function">getOwner</span><span class="token punctuation">(</span>path<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//擁有者:DESKTOP-GE36VVD\87772 (User)</span> <span class="token comment">//System.out.println(Files.getPosixFilePermissions(path));//權限,非admin可能會報錯</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>Files<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span>path<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//文件大小: 34207517</span> <span class="token punctuation">}</span> <span class="token comment">/** * 讀取一個文本文件 */</span> <span class="token annotation punctuation">@Test</span> <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">readText</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> IOException <span class="token punctuation">{<!-- --></span> Path path <span class="token operator">=</span> Paths<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">"F:/test.txt"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//經過bufferedReader讀取</span> BufferedReader bufferedReader <span class="token operator">=</span> Files<span class="token punctuation">.</span><span class="token function">newBufferedReader</span><span class="token punctuation">(</span>path<span class="token punctuation">,</span> StandardCharsets<span class="token punctuation">.</span>UTF_8<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">///該文件編碼是什麼newBufferedReader就必須指定什麼字符集,不然報錯</span> StringBuilder sb <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">StringBuilder</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> String tempString <span class="token operator">=</span> null<span class="token punctuation">;</span> <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token punctuation">(</span>tempString <span class="token operator">=</span> bufferedReader<span class="token punctuation">.</span><span class="token function">readLine</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">!=</span> null<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span> sb <span class="token operator">=</span> sb<span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>tempString <span class="token operator">+</span> <span class="token string">"\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>sb<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//經過Files方法readAllLines</span> List<span class="token generics function"><span class="token punctuation"><</span>String<span class="token punctuation">></span></span> strings <span class="token operator">=</span> Files<span class="token punctuation">.</span><span class="token function">readAllLines</span><span class="token punctuation">(</span>path<span class="token punctuation">)</span><span class="token punctuation">;</span> strings<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span>System<span class="token punctuation">.</span>out<span class="token operator">:</span><span class="token operator">:</span>println<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token comment">/** * 拿到文件輸入流 * * @throws IOException */</span> <span class="token annotation punctuation">@Test</span> <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">getInputStream</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> IOException <span class="token punctuation">{<!-- --></span> Path path <span class="token operator">=</span> Paths<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">"F:/test.txt"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> InputStream inputStream <span class="token operator">=</span> Files<span class="token punctuation">.</span><span class="token function">newInputStream</span><span class="token punctuation">(</span>path<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//轉換字符流後在包裝成緩衝流</span> BufferedReader bufferedReader <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BufferedReader</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">InputStreamReader</span><span class="token punctuation">(</span>inputStream<span class="token punctuation">,</span> <span class="token string">"UTF-8"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span> StringBuilder sb <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">StringBuilder</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> String tempString <span class="token operator">=</span> null<span class="token punctuation">;</span> <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token punctuation">(</span>tempString <span class="token operator">=</span> bufferedReader<span class="token punctuation">.</span><span class="token function">readLine</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">!=</span> null<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span> sb <span class="token operator">=</span> sb<span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>tempString <span class="token operator">+</span> <span class="token string">"\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>sb<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token comment">/** * 文件寫操做 */</span> <span class="token annotation punctuation">@Test</span> <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">writeFile</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> IOException <span class="token punctuation">{<!-- --></span> Path path <span class="token operator">=</span> Paths<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">"F:/writeFile.txt"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//獲取寫入流</span> BufferedWriter bufferedWriter <span class="token operator">=</span> Files<span class="token punctuation">.</span><span class="token function">newBufferedWriter</span><span class="token punctuation">(</span>path<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//執行寫入操做</span> String str <span class="token operator">=</span> <span class="token string">"write file test"</span><span class="token punctuation">;</span> bufferedWriter<span class="token punctuation">.</span><span class="token function">write</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//關閉資源</span> bufferedWriter<span class="token punctuation">.</span><span class="token function">flush</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> bufferedWriter<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token comment">/** * 遍歷一個文件夾 */</span> <span class="token annotation punctuation">@Test</span> <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">traverseDirectory</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> IOException <span class="token punctuation">{<!-- --></span> Path path <span class="token operator">=</span> Paths<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">"F:/test"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> Stream<span class="token generics function"><span class="token punctuation"><</span>Path<span class="token punctuation">></span></span> list <span class="token operator">=</span> Files<span class="token punctuation">.</span><span class="token function">list</span><span class="token punctuation">(</span>path<span class="token punctuation">)</span><span class="token punctuation">;</span> list<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span>p <span class="token operator">-</span><span class="token operator">></span> <span class="token punctuation">{<!-- --></span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>p<span class="token punctuation">.</span><span class="token function">getFileName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token comment">/** * 遍歷文件樹 */</span> <span class="token annotation punctuation">@Test</span> <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">traverseTree</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> IOException <span class="token punctuation">{<!-- --></span> Path path <span class="token operator">=</span> Paths<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">"F:/test/"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> Stream<span class="token generics function"><span class="token punctuation"><</span>Path<span class="token punctuation">></span></span> walk <span class="token operator">=</span> Files<span class="token punctuation">.</span><span class="token function">walk</span><span class="token punctuation">(</span>path<span class="token punctuation">)</span><span class="token punctuation">;</span> walk<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span>path1 <span class="token operator">-</span><span class="token operator">></span> <span class="token punctuation">{<!-- --></span>
// System.out.println(path1.getRoot());//根目錄
System.out.println(path1.getFileName());//文件名
// System.out.println(path1.getParent());//上級目錄
// System.out.println(path1.getFileSystem());//文件系統
});
//還有種方式Files.walkFileTree()
}
<span class="token comment">/** * 文件複製 */</span> <span class="token annotation punctuation">@Test</span> <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">copyFile</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> IOException <span class="token punctuation">{<!-- --></span> Path src <span class="token operator">=</span> Paths<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">"F:/測試數據.csv"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> Path dest <span class="token operator">=</span> Paths<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">"F:/test/Copy測試數據.csv"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> Files<span class="token punctuation">.</span><span class="token function">copy</span><span class="token punctuation">(</span>src<span class="token punctuation">,</span> dest<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token comment">/** * 讀取權限見上面示例,設置權限 */</span> <span class="token annotation punctuation">@Test</span> <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">writePermission</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> IOException <span class="token punctuation">{<!-- --></span> Path path <span class="token operator">=</span> Paths<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">"F:/test/導出測試數據.xlsx"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> Set<span class="token generics function"><span class="token punctuation"><</span>PosixFilePermission<span class="token punctuation">></span></span> permissionSet <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">HashSet</span><span class="token operator"><</span><span class="token operator">></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> permissionSet<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>PosixFilePermission<span class="token punctuation">.</span>GROUP_WRITE<span class="token punctuation">)</span><span class="token punctuation">;</span> permissionSet<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>PosixFilePermission<span class="token punctuation">.</span>OWNER_EXECUTE<span class="token punctuation">)</span><span class="token punctuation">;</span> Files<span class="token punctuation">.</span><span class="token function">setPosixFilePermissions</span><span class="token punctuation">(</span>path<span class="token punctuation">,</span> permissionSet<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span>
/**
* 判斷方法
* @throws IOException
*/
@Test
public void judge() throws IOException {
Path path1 = Paths.get(「f:\test」, 「Copy測試數據.csv」);
Path path2 = Paths.get(「f:\測試數據.csv」);
// boolean exists(Path path, LinkOption … opts) : 判斷文件是否存在
System.out.println(Files.exists(path2, LinkOption.NOFOLLOW_LINKS));//true
// boolean isDirectory(Path path, LinkOption … opts) : 判斷是不是目錄
//不要求此path對應的物理文件存在。
System.out.println(Files.isDirectory(path1, LinkOption.NOFOLLOW_LINKS));//false
// boolean isRegularFile(Path path, LinkOption … opts) : 判斷是不是文件
// boolean isHidden(Path path) : 判斷是不是隱藏文件
//要求此path對應的物理上的文件須要存在。纔可判斷是否隱藏。不然,拋異常。
// System.out.println(Files.isHidden(path1));
// boolean isReadable(Path path) : 判斷文件是否可讀
System.out.println(Files.isReadable(path1));//true
// boolean isWritable(Path path) : 判斷文件是否可寫
System.out.println(Files.isWritable(path1));//true
// boolean notExists(Path path, LinkOption … opts) : 判斷文件是否不存在
System.out.println(Files.notExists(path1, LinkOption.NOFOLLOW_LINKS));//false
}
}
<span class="token comment">/** * StandardOpenOption.READ:表示對應的Channel是可讀的。 * StandardOpenOption.WRITE:表示對應的Channel是可寫的。 * StandardOpenOption.CREATE:若是要寫出的文件不存在,則建立。若是存在,忽略 * StandardOpenOption.CREATE_NEW:若是要寫出的文件不存在,則建立。若是存在,拋異常 */</span> <span class="token annotation punctuation">@Test</span> <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">ioStream</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> IOException <span class="token punctuation">{<!-- --></span> Path path1 <span class="token operator">=</span> Paths<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">"f:\\test"</span><span class="token punctuation">,</span> <span class="token string">"copyTest.txt"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
// InputStream newInputStream(Path path, OpenOption…how):獲取 InputStream 對象
InputStream inputStream = Files.newInputStream(path1, StandardOpenOption.READ);
// OutputStream newOutputStream(Path path, OpenOption…how) : 獲取 OutputStream 對象
OutputStream outputStream = Files.newOutputStream(path1, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
// SeekableByteChannel newByteChannel(Path path, OpenOption…how) : 獲取與指定文件的鏈接,how 指定打開方式。
SeekableByteChannel channel = Files.newByteChannel(path1, StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
// DirectoryStream<Path> newDirectoryStream(Path path) : 打開 path 指定的目錄
Path path2 = Paths.get(「f:\test」);
DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path2);
Iterator<Path> iterator = directoryStream.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
五.FileTime對象
表示文件時間戳屬性的值,可能會在設置文件最後更新屬性時使用到:
栗子:
/** * 可能你要從文件屬性中的FileTime或者到一個Date對象 */ Path pathObj = Paths.get("C:/a/b/c.txt"); BasicFileAttributes attrs = Files.readAttributes(pathObj, BasicFileAttributes.class); Data date = new Date(attrs.lastModifiedTime().toMillis());
/**
- 又或者可能你要人爲地修改這個文件時間屬性,須要一個FileTime
*/
Path path = Paths.get(「C:/a/b/c.txt」);
long time = System.currentTimeMillis();
FileTime fileTime = FileTime.fromMillis(time);
try{
Files.setAttribute(path, 「basic:lastModifiedTime」, fileTime,LinkOption.NOFOLLOW_LINKS);
}catch (IOException e) {
System.err.println(e);
}