【发布时间】:2021-04-26 23:14:20
【问题描述】:
我使用下面的代码来比较 Java 中的两个 Path:
import java.nio.file.Paths;
public class PathTest {
public static void main(String args[]) {
String path1 = "path1\\file1.jpg";
String path2 = "path1/file1.jpg";
System.out.println(Paths.get(path1));
System.out.println(Paths.get(path2));
System.out.println(Paths.get(path1).equals(Paths.get(path2)));
}
}
我确实在我的 Windows 机器上得到以下输出:
path1\file1.jpg
path1\file1.jpg
true
在 linux 上:
path1\file1.jpg
path1/file1.jpg
false
这是怎么回事?
【问题讨论】:
-
“两个路径是否相等取决于文件系统实现”。 Windows在这里比Linux更宽容。 docs.microsoft.com/en-us/dotnet/standard/io/file-path-formats "所有正斜杠 (/) 都转换为标准的 Windows 分隔符,反斜杠 ()。"
-
是的,你是对的。字符串的印刷也很愚蠢。我想打印路径对象,我将调整示例。在 Windows 上,斜线会发生转换。谢谢!
标签: java path operating-system equals environment