gpt4 book ai didi

java - filePath.getFileName() 的行为不同

转载 作者:行者123 更新时间:2023-12-01 23:32:31 25 4
gpt4 key购买 nike

我尝试使用Path接口(interface);

//get a path object with relative path
Path filePath = Paths.get("C:\\Test\\filename.txt");
System.out.println("The file name is: " + filePath.getFileName());
Path filePath2 = Paths.get("/home/shibu/Desktop/filename.txt");
System.out.println("The file name is: " + filePath2.getFileName());

输出就像;

The file name is: C:\Test\filename.txt
The file name is: filename.txt

对于 Windows 文件,它打印完整路径,对于 Linux 文件,它仅打印文件名。

为什么会出现这种差异?

最佳答案

简单:在 Linux 上,文件名中唯一的非法字符是 / 和 0 字节。其他所有内容(包括 \、换行符和转义序列)均有效。

这意味着 C:\Test\filename.txt 是 Linux 上的有效文件名。 Java 运行时不会试图变得聪明并猜测这可能是 Windows 路径。

请注意,使用 / 时情况有所不同:这是使用 Java 时 Windows 上的有效路径分隔符。因此,路径 a/foo.txt 在 Linux Windows 上都是相对路径。

这意味着您可以使用 Paths.get("/C:/Test/filename.txt"); 在 Windows 上打开文件。

关于java - filePath.getFileName() 的行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19113624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com