简体   繁体   English

Windows和Linux中用于Java代码的路径分隔符

[英]Path delimiter in windows and linux for java code

In my java code, I have some hard coded paths which I have written as 在我的Java代码中,我有一些硬编码的路径,它们写为

String workingPath = initPath + "\\" + tmpPath;

the initPath and tmpPath are obtained by File.getParent() . initPathtmpPath是通过File.getParent()获得的。 Now, that works on windows and if I move my code to linux, the \\\\ will be problematic since the other two are determined by system methods. 现在,它可以在Windows上运行,并且如果我将代码移至linux,则\\\\将是有问题的,因为其他两个是由系统方法确定的。 The results is something like this 结果是这样的

/home/mahmood/project/alpha\temp1

How can I fix that? 我该如何解决? I don't want to put / in my code for linux systems. 我不想在Linux系统的代码中加入/

There is a variable you can use: File.separator 您可以使用一个变量: File.separator

The system-dependent default name-separator character, represented as a string for convenience. 系统相关的默认名称分隔符,为方便起见,以字符串形式表示。 This field is initialized to contain the first character of the value of the system property file.separator. 初始化此字段以包含系统属性file.separator值的第一个字符。 On UNIX systems the value of this field is '/'; 在UNIX系统上,此字段的值为'/'; on Microsoft Windows systems it is '\\'. 在Microsoft Windows系统上,它是'\\'。

String workingPath = initPath + File.separator + tmpPath;

The File class has a constructor that accepts a parent directory. File类具有一个接受父目录的构造函数。 If you use this, you don't need to manually concatenate paths. 如果使用此选项,则无需手动连接路径。

final File parent = new File("/home/mahmood/project/alpha");
final File tmp = new File(parent, "temp1");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM