1

In my program, I am reading a resource file for a unit test. I use file path as:

\\\path\\\to\\\file

On my machine(Windows) this runs fine. But on server(Unix), this fails, and I have to change it to: /path/to/file

But Java is supposed to be platform independent. So isn't this behaviour unexpected?

Tamas Rev
  • 7,008
  • 5
  • 32
  • 49
Mandroid
  • 6,200
  • 12
  • 64
  • 134

5 Answers5

5

Use FileSystem.getSeparator() or System.getProperty("file.separator") instead of using slashes.

EDIT: You can get an instance of FileSystem via FileSystems.getDefault (JDK 1.7+)

starman1979
  • 974
  • 4
  • 12
  • 33
3

You can use File.separator to get the appropriate character in a platform-independent way.

apetranzilla
  • 5,331
  • 27
  • 34
1

Java is platform independent. The file path-es and some system calls are not.

As long as the path is relative, you can use File.separator:

    String path = "path" + File.separator + "to" + File.separator + "file";
    System.out.println(path); // prints path\to\file on windows

Sometimes it's an option is to provide a Properties file and let the user define path of that actual file. This way full paths are okay too. You can read the properties like this:

    Properties props = new Properties();
    props.load(new FileInputStream(filePath));

The next question is: how to specify the location of that file? That might be either a file on a relative path. If that's not viable for your app, then you can let the user specify it in a system property:

java ... -DconfigFile=C:\TEMP\asd.txt .... -jar myapp.jar

Then you can access it like this:

// prints C:\TEMP\asd.txt if you specified -DconfigFile=C:\TEMP\asd.txt
System.out.println(System.getProperty("configFile"));
Tamas Rev
  • 7,008
  • 5
  • 32
  • 49
0

This is the expected behaviour.

Java code compiles on any machine/OS provided you have the right version of Java installed on it.

However, at run time, your code sees only a variable value like another one, which happens to be \path\to\file

When it talks to the file system, it uses that particular value ; the file system then tries to find that path you've given to it ; which is why one syntax works fine on Windows but will not work on Linux.

0

Better way of doing this is :

val pathUri = Paths.get(".//src//test//res//file.txt").toUri()
val is = FileInputStream((File(pathUri)))
Minion
  • 964
  • 14
  • 16