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?

1

5 Answers 5

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+)

Sign up to request clarification or add additional context in comments.

1 Comment

You might want to clarify how to acquire a FileSystem instance
3

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

Comments

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"));

Comments

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.

Comments

0

Better way of doing this is :

val pathUri = Paths.get(".//src//test//res//file.txt").toUri()
val is = FileInputStream((File(pathUri)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.