Path delimiter in windows and linux for java code
Asked Answered
V

2

9

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.

Vesuvian answered 29/5, 2017 at 20:38 Comment(2)
You can use / on both Windows and Linux, another option is to use File(File, String) to build your paths.Copalm
@ElliottFrisch Your comment is a good solution, it should be an answer post.Holliman
S
21

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;
Supersaturated answered 29/5, 2017 at 20:42 Comment(0)
P
4

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");
Plausible answered 29/5, 2017 at 20:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.