2

我有以下java代码:

public interface Defaults {
  public static final String DIR_PATH = "a/b/c/";
  File DIR_FILE = new File(DIR_PATH);
}

public class Main {
  public File directory = Defaults.DIR_FILE;
}

这是在 Windows 机器上编译并部署到我们本地的 nexus 存储库。然后在 linux 机器上的 maven 构建期间执行它。我最终main.directory.list()返回null。使用mvnDebug,我看到文件的路径实际上是a\b\c!如果我使用调试器将目录更改为new File("a/b/c"),那么我的代码就可以工作。

为什么编译器对系统特定的分隔符进行编码?有解决办法吗?

4

4 回答 4

3

Unlike what everyone else tells you, this is unrelated to Windows and File.separator.

String DIR_PATH = "a/b/c/" is just a String, neither Java nor the compiler make any attempt to understand what it could mean, so you get the same value both on Windows and Linux.

Also note that / works as a file separator both on Unix and Windows, so this isn't an issue either. When necessary, Java will convert / to \.

File DIR_FILE = new File(DIR_PATH); is a constant but new File() is still executed by the VM at runtime when the class is loaded. So the path is not converted to Windows format while the compiler generates byte code.

So the problem you describe must be elsewhere or an important part of the code example you posted was changed when you simplified it for the question. My guess is that someone put a Windows-style path into the code elsewhere or maybe the config and you overlooked this.

That said, a safe way to build paths is to use File(File, String):

File DIR_PATH = new File( "a", new File( "b", "c" ) );

This will always build a path that works, no matter what the file separator is. If you must, you can use

File DIR_PATH = "a" + File.separator + "b" + File.separator + "c";

but that can fail for more complex examples and it's more text to read.

于 2013-05-06T09:27:02.953 回答
2

是的使用File.separatorChar

系统相关的默认名称分隔符。该字段被初始化为包含系统属性 file.separator 值的第一个字符。在 UNIX 系统上,该字段的值为 '/';在 Microsoft Windows 系统上,它是 '\'。

于 2013-05-06T08:47:02.857 回答
1

使用与平台无关的文件/目录分隔符,例如File.separator

于 2013-05-06T08:50:03.780 回答
0
public static final String DIR_PATH = "a"+File.separator"+"b"+File.separator+"c"
于 2013-05-06T08:51:33.390 回答