Aneesh
Aneesh

Reputation: 151

filePath.getFileName() behaves differently

I tried the use of Path interface;

//get a path object with relative path
Path filePath = Paths.get("C:\\Test\\filename.txt");
System.out.println("The file name is: " + filePath.getFileName());
Path filePath2 = Paths.get("/home/shibu/Desktop/filename.txt");
System.out.println("The file name is: " + filePath2.getFileName());

The out put is like;

The file name is: C:\Test\filename.txt
The file name is: filename.txt

For the windows file it printed full path and for linux file it printed only file name.

Why this difference?

Upvotes: 0

Views: 229

Answers (1)

Aaron Digulla
Aaron Digulla

Reputation: 328714

Simple: On Linux, the only illegal characters in a file name are / and the 0 byte. Everything else, including \, line feed and escape sequences, are valid.

That means C:\Test\filename.txt is a valid file name on Linux. The Java runtime doesn't attempt to be smart and guess that this might be a Windows path.

Note that this is different when you use /: This is a valid path delimiter on Windows when using Java. So the path a/foo.txt is a relative path both on Linux and Windows.

This means you can open files on Windows using Paths.get("/C:/Test/filename.txt");, for example.

Upvotes: 3

Related Questions