I have a situation in which I receive a File URI in the format
file:///home/user/a.txt
I know that depending of the operation system other formats can be expected:
file:/C:/a.txt <- On Windows
file:///C:/a.txt <- On Windows
file:///home/user/a.txt <- On Linux
I need the absolute file path to store the file. So I want to convert:
file:///home/user/a.txt ===> /home/user/a.txt
I do now this in a very clumsy way:
public void save(URI targetURI) {
Path path = Paths.get("/", targetURI.toString()).normalize();
String filePath="" path;
filePath=filePath.replace("/file:", "");
....
}
I expect there is a more elegant solution based on the java.io util classes?
CodePudding user response:
check this -> Convert URL to AbsolutePath
Path p = Paths.get(url.toURI());
and how say @GOTO 0
Another option for those who use Java 11 or later:
Path path = Path.of(url.toURI()); or as a string:
String path = Path.of(url.toURI()).toString(); Both methods above throw a URISyntaxException that can be safely ignored if the URL is guaranteed to be a file URL.
UPDATE
And i found this -> https://eed3si9n.com/encoding-file-path-as-URI-reference/ The solution to the problem is described in great detail here
public static void main(String[] args) throws URISyntaxException
{
URI uri = new URI("file:/C:/a.txt");
save(uri);
uri = new URI("file:///C:/a.txt");
save(uri);
uri = new URI("file:///home/user/a.txt");
save(uri);
}
public static void save(URI targetURI)
{
Path p = Paths.get(targetURI);
String absolutePath = p.toString();
System.out.println(absolutePath);
}
CodePudding user response:
ok, quite simple
public void save(URI targetURI) {
Path p=Paths.get(targetURI).toString());
String absolutePath= p.toString();
...
}