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、

 

posted @ 2023-01-28 19:23  快乐的欧阳天美1114  阅读(603)  评论(0编辑  收藏  举报