Java:Path及Paths使用

Java 8

Windows 10

--

 

主要內容:

Windows 下測試,組合文件路徑、Path 轉 File 等。

 

準備:

D盤;

D盤下 bootweb目錄(spring boot項目);

D盤下 test.txt文件;

D盤下 其它目錄及文件;

 

要區分 相對路徑、絕對路徑。

 

測試代碼:

Path path = Paths.get("d");
System.out.println("1、" + path + ", " + path.isAbsolute() + ", " + path.getFileSystem().isOpen());
File file = path.toFile();
System.out.println("1、file=" + file + ", " + file.exists());

path = Paths.get("d:");
System.out.println("2、" + path + ", " + path.isAbsolute() + ", " + path.getFileSystem().isOpen());

path = Paths.get("d:/");
System.out.println("3、" + path + ", " + path.isAbsolute() + ", " + path.getFileSystem().isOpen());file = path.toFile();
System.out.println("3、file=" + file + ", " + file.exists());

path = Paths.get("d:\\");
System.out.println("4、" + path + ", " + path.isAbsolute() + ", " + path.getFileSystem().isOpen());

path = Paths.get("d:", "test.txt");
System.out.println("5、" + path + ", " + path.isAbsolute() + ", " + path.getFileSystem().isOpen());

path = Paths.get("d", "test.txt");
System.out.println("6、" + path + ", " + path.isAbsolute() + ", " + path.getFileSystem().isOpen());

path = Paths.get("d:", "ws/path2/readme.txt");
System.out.println("7、" + path + ", " + path.isAbsolute() + ", " + path.getFileSystem().isOpen());

path = Paths.get("d:\\ws/path2/readme.txt");
System.out.println("8、" + path + ", " + path.isAbsolute() + ", " + path.getFileSystem().isOpen());

path = Paths.get("d:", "ws", "path2", "readme.txt");
System.out.println("9、" + path + ", " + path.isAbsolute() + ", " + path.getFileSystem().isOpen());

path = Paths.get("D:\\bootweb", "src", "main", "java");
System.out.println("10、" + path + ", " + path.isAbsolute() + ", " + path.getFileSystem().isOpen());
file = path.toFile();
System.out.println("10、file=" + file + ", " + file.exists());

 

測試結果:

1、d, false, true
1、file=d, false
2、d:, false, true
3、d:\, true, true
3、file=d:\, true
4、d:\, true, true
5、d:\test.txt, true, true
6、d\test.txt, false, true
7、d:\ws\path2\readme.txt, true, true
8、d:\ws\path2\readme.txt, true, true
9、d:\ws\path2\readme.txt, true, true
10、D:\bootweb\src\main\java, true, true
10、file=D:\bootweb\src\main\java, true

 

本文鏈接:

https://www.cnblogs.com/luo630/p/17070524.html

 

參考資料

1、【轉載】瞭解java.nio.file.Path – 1

https://blog.csdn.net/dnc8371/article/details/106702332

2、

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章