Path delimiter in windows and linux for java code

☆樱花仙子☆ 提交于 2020-01-30 02:47:15

问题


In my java code, I have some hard coded paths which I have written as

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

the initPath and tmpPath are obtained by 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. 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.


回答1:


There is a variable you can use: 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. On UNIX systems the value of this field is '/'; on Microsoft Windows systems it is '\'.

String workingPath = initPath + File.separator + tmpPath;



回答2:


The File class has a constructor that accepts a parent directory. 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");


来源:https://stackoverflow.com/questions/44250017/path-delimiter-in-windows-and-linux-for-java-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!