1

I need to construct a file path inside a java program. Which path separator should I use to
allow my program to work on both Windows and Unix?

Keep in mind that Windows needs a drive letter.

Sree Ram
  • 819
  • 3
  • 12
  • 22

6 Answers6

2

Use System.getProperty("file.separator").

Andrew Logvinov
  • 21,181
  • 6
  • 52
  • 54
2

You can use Java's File.separator for system independence.

separator is a static String member of the File class.

Here's an example and here's the javadoc for File.

EDIT - Getting the OS info

If you only want to see wether you should add a the C:, have a look at this example for getting the OS info, then parse the OS string and see whether it's MS Windows.

You may also find question 1298310 useful for getting all drive information.

Community
  • 1
  • 1
lucian.pantelimon
  • 3,673
  • 4
  • 29
  • 46
2

Use File.separator to be platform independent although forward slash / works on both windows and unix.

Moreover I'd suggest you to avoid using File.separator. If you want to create file in folder do the following:

File dir = new File("myfolder"); // no slashes
File file = new File(dir, "myfile.txt"); // no slashes.

Use File.listRoots() to get all driver letters on Windows or single file root / on Unix.

AlexR
  • 114,158
  • 16
  • 130
  • 208
0

Use File.separator to construct your file paths.

adarshr
  • 61,315
  • 23
  • 138
  • 167
0

You should use java.io.File.separator -> http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html#separator

zbyszek26104
  • 437
  • 1
  • 5
  • 15
0

use File.seperator for seperator for any operating system.

Balaswamy Vaddeman
  • 8,360
  • 3
  • 30
  • 40