[英]Path.equals behaves different on Windows and Linux
I use the following code to compare two Paths in Java:我使用下面的代码来比较 Java 中的两个 Paths:
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)));
}
}
I do get the following output on my Windows machine:我在我的 Windows 机器上得到了以下 output :
path1\file1.jpg
path1\file1.jpg
true
And on linux:在 linux 上:
path1\file1.jpg
path1/file1.jpg
false
What's going on here?这里发生了什么?
Path separator is different for Windows and Linux. Windows 和 Linux 的路径分隔符不同。
For Windows is \
对于 Windows 是
\
For Linux is /
对于 Linux 是
/
Safe way in java of building paths that work on both evironments is java 中适用于两种环境的建筑路径的安全方式是
Path filePath = Paths.get("path1", "path2");
In your case you use a String to form a Path.在您的情况下,您使用字符串来形成路径。 So in Windows
所以在 Windows
String path2 = "path1/file1.jpg";
Paths.get(path2) -> results in "path1\file1.jpg"
It converts the separator /
to a windows separator \
它将分隔符
/
转换为 windows 分隔符\
After that conversion both path1 and path2 are the same转换后 path1 和 path2 都相同
Now when you run in Linux the following code现在,当您在 Linux 中运行以下代码时
String path1 = "path1\\file1.jpg"; -> this will not be ok for linux and also will not try to convert it to / as the first \ is an escape character
String path2 = "path1/file1.jpg"; -> this will be ok for linux /
System.out.println(Paths.get(path1));
System.out.println(Paths.get(path2));
System.out.println(Paths.get(path1).equals(Paths.get(path2)));
/
is the path separator on Unix and Unix-like systems like Linux. /
是 Unix 和类 Unix 系统(如 Linux)上的路径分隔符。 Modern Windows operating systems can use both \
and /
as path separator.现代 Windows 操作系统可以使用
\
和/
作为路径分隔符。
If you develop for Windows and Linux you can generally use /
as a path separator and don't bother using File.separator
.如果您为 Windows 和 Linux 进行开发,您通常可以使用
/
作为路径分隔符,而不必费心使用File.separator
。 For example Java on Windows resolves all these pathnames correctly without "\\"
in a String, even UNC format:例如,Windows 上的 Java 可以正确解析所有这些路径名,而无需字符串中的
"\\"
,甚至 UNC 格式:
var unc = Path.of("//storage/media/camera");
// ==> \\storage\media\camera
var mdrive = Path.of("M:/camera");
// ==> M:\camera
var build = Path.of("build/classes");
// ==> build\classes
var a= Path.of("/Temp");
// ==> \Temp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.