首页 > 解决方案 > Path.equals 在 Windows 和 Linux 上的行为不同

问题描述

我使用以下代码来比较 Java 中的两个路径:

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

这里发生了什么?

标签: javapathoperating-systemequalsenvironment

解决方案


/是 Unix 和类 Unix 系统(如 Linux)上的路径分隔符。现代 Windows 操作系统可以同时使用\/作为路径分隔符。


推荐阅读