路徑類
Java SE 7版本中引入的Path類是java.nio.file包的主要入口點之一。如果您的應用程序使用文件I / O,您將需要了解此類的強大功能。
版本注意:如果您有使用java.io.File的JDK7之前的代碼,則仍然可以使用File.toPath方法來利用Path類功能。有關詳細信息,請參閱傳統文件I / O代碼。
顧名思義,Path類是文件系統中路徑的編程表示形式。路徑對象包含用於構建路徑的文件名和目錄列表,用於檢查,定位和操作文件。
路徑實例反映了底層平臺。在Solaris OS中,路徑使用Solaris語法(/ home / joe / foo),而在Microsoft Windows中,路徑使用Windows語法(C:\ home \ joe \ foo)。路徑與系統無關。您不能將Solaris與Solaris文件系統進行比較,並期望它與Windows文件系統中的路徑相匹配,即使目錄結構相同,並且兩個實例都找到相同的相對文件。
與Path相對應的文件或目錄可能不存在。您可以創建一個Path實例並以各種方式進行操作:您可以附加它,提取它,並將其與其他路徑進行比較。在適當的時候,您可以使用Files類中的方法檢查與Path對應的文件的存在,創建文件,打開它,刪除它,更改其權限等。
下一頁將詳細介紹Path類。
路徑操作
簡介
創建一個路徑
Path p1 = Paths.get("/tmp/foo");
Path p2 = Paths.get(args[0]);
Path p3 = Paths.get(URI.create("file:///Users/joe/FileTest.java"));
Paths.get方法是以下代碼的縮寫:Path p4 = FileSystems.getDefault().getPath("/users/sally");
以下示例創建/u/joe/logs/foo.log,假設您的主目錄是/ u / joe,或者C:\ joe \ logs \ foo.log(如果您在Windows上)。
Path p5 = Paths.get(System.getProperty("user.home"),"logs", "foo.log");
檢索路徑信息
// None of these methods requires that the file corresponding
// to the Path exists.
// Microsoft Windows syntax
Path path = Paths.get("C:\\home\\joe\\foo");
// Solaris syntax
Path path = Paths.get("/home/joe/foo");
System.out.format("toString: %s%n", path.toString());
System.out.format("getFileName: %s%n", path.getFileName());
System.out.format("getName(0): %s%n", path.getName(0));
System.out.format("getNameCount: %d%n", path.getNameCount());
System.out.format("subpath(0,2): %s%n", path.subpath(0,2));
System.out.format("getParent: %s%n", path.getParent());
System.out.format("getRoot: %s%n", path.getRoot());
以下是Windows和Solaris操作系統的輸出:上一個示例顯示絕對路徑的輸出。在以下示例中,指定了相對路徑:
// Solaris syntax
Path path = Paths.get("sally/bar");
or
// Microsoft Windows syntax
Path path = Paths.get("sally\\bar");
以下是Windows和Solaris OS的輸出:從路徑中刪除冗餘數據
/home/sally/../joe/foo
轉換路徑
Path p1 = Paths.get("/home/logfile");
// Result is file:///home/logfile
System.out.format("%s%n", p1.toUri());
toAbsolutePath方法將路徑轉換爲絕對路徑。如果傳入路徑已經是絕對路徑,則返回相同的路徑對象。在處理用戶輸入的文件名時,toAbsolutePath方法非常有用。例如:public class FileTest {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("usage: FileTest file");
System.exit(-1);
}
// Converts the input string to a Path object.
Path inputPath = Paths.get(args[0]);
// Converts the input Path
// to an absolute path.
// Generally, this means prepending
// the current working
// directory. If this example
// were called like this:
// java FileTest foo
// the getRoot and getParent methods
// would return null
// on the original "inputPath"
// instance. Invoking getRoot and
// getParent on the "fullPath"
// instance returns expected values.
Path fullPath = inputPath.toAbsolutePath();
}
}
toAbsolutePath方法轉換用戶輸入並返回一個在查詢時返回有用值的路徑。該文件不需要存在,以使此方法正常工作。 try {
Path fp = path.toRealPath();
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n", path);
// Logic for case when file doesn't exist.
} catch (IOException x) {
System.err.format("%s%n", x);
// Logic for other sort of file error.
}
聯合兩個路徑
// Solaris
Path p1 = Paths.get("/home/joe/foo");
// Result is /home/joe/foo/bar
System.out.format("%s%n", p1.resolve("bar"));
或者// Microsoft Windows
Path p1 = Paths.get("C:\\home\\joe\\foo");
// Result is C:\home\joe\foo\bar
System.out.format("%s%n", p1.resolve("bar"));
將絕對路徑傳遞給resolve方法返回傳入路徑:// Result is /home/joe
Paths.get("foo").resolve("/home/joe");
在兩個路徑之間創建一個新的路徑
Path p1 = Paths.get("joe");
Path p2 = Paths.get("sally");
對於其他信息而言,假設 Joe 和 Sally是兄妹,這意味着這個節點在樹結構中有着同等的等級。 要想通過 Joe找到Sally,你可能需要首先找到這個父節點,然後找到Sally。// Result is ../sally
Path p1_to_p2 = p1.relativize(p2);
// Result is ../joe
Path p2_to_p1 = p2.relativize(p1);
再看一個略微複雜的例子:Path p1 = Paths.get("home");
Path p3 = Paths.get("home/sally/bar");
// Result is sally/bar
Path p1_to_p3 = p1.relativize(p3);
// Result is ../..
Path p3_to_p1 = p3.relativize(p1);
在這個例子中,兩個路徑共享了一個節點:home。 從home找到了bar,首先需要找到一個等級(home),然後再查找下一個等級找到Sally,最後再找到bar。從bar要找到home,需要向上查找兩個等級。這個Copy 的遞歸例子,使用了relativize 和 resolve 方法。
比較兩個路徑
Path path = ...;
Path otherPath = ...;
Path beginning = Paths.get("/home");
Path ending = Paths.get("foo");
if (path.equals(otherPath)) {
// equality logic here
} else if (path.startsWith(beginning)) {
// path begins with "/home"
} else if (path.endsWith(ending)) {
// path ends with "foo"
}
Path類實現了Iterable接口,iterator方法返回一個對象,而這個對象讓你可以遍歷路徑中的所有節點名稱。第一個被返回的節點,是離目錄樹最近的根節點。下面的代碼簡單的遍歷了一個路徑,並打印每一個節點的名稱:
Path path = ...;
for (Path name: path) {
System.out.println(name);
}
Path類同樣實現了comparable接口,你可以比較路徑對象通過comparaTo方法,這個方法對於排序也同樣有用。