Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the path string from a java.nio.Path?

Tags:

java

file

nio

Rewrote question with more info

I have some code that creates a Path object using relative paths, like this: Paths.get("..", "folder").resolve("filename"). Later, I want to get the path string "..\folder\filename" from it (I'm on windows, so backslashes). When I run this code using manual compile or from Eclipse, this works fine.

However, when I run it using Maven, it doesn't work any more. The toString() method returns [.., folder, filename] instead of an actual path string. Using path.normalize() doesn't help. Using path.toFile().getPath() does return what I'm looking for, but I feel there should be a solution using just the nio.path API.

like image 967
Jorn Avatar asked Jul 09 '13 15:07

Jorn


People also ask

What is Java NIO file paths?

Advertisements. As name suggests Path is the particular location of an entity such as file or a directory in a file system so that one can search and access it at that particular location.

How do I find the path of a file in Java?

In Java, for NIO Path, we can use path. toAbsolutePath() to get the file path; For legacy IO File, we can use file. getAbsolutePath() to get the file path.

What is the use of @path in Java?

A Path can represent a root, a root and a sequence of names, or simply one or more name elements. A Path is considered to be an empty path if it consists solely of one name element that is empty. Accessing a file using an empty path is equivalent to accessing the default directory of the file system.


2 Answers

Use:

Paths.get(...).normalize().toString() 

Another solution woul be:

Paths.get(...).toAbsolutePath().toString() 

However, you get strange results: Paths.get("/tmp", "foo").toString() returns /tmp/foo here. What is your filesystem?

like image 155
fge Avatar answered Sep 22 '22 17:09

fge


To complete the the fge's answer, I would add some info:

  1. normalize() simply removes redundant pieces of strings in your path, like . or ..; it does not operate at the OS level or gives you an absolute path from a relative path
  2. toAbsolutePath() on the contrary gives you what the name says, the absolute path of the Path object. But...
  3. toRealPath() resolves also soft and hard links (yes they exists also on Windows, so win user, you're not immune). So it gives to you, as the name says, the real path.

So what's the best? It depends, but personally I use toRealPath() the 99% of the cases.

Source: Official javadoc

like image 24
Marco Sulla Avatar answered Sep 22 '22 17:09

Marco Sulla