Convert File Path to a File Uri

Convert file path to a file URI?

The System.Uri constructor has the ability to parse full file paths and turn them into URI style paths. So you can just do the following:

var uri = new System.Uri("c:\\foo");
var converted = uri.AbsoluteUri;

Convert a file path to Uri in Android

Please try the following code

Uri.fromFile(new File("/sdcard/sample.jpg"))

Convert file: Uri to File in Android

What you want is...

new File(uri.getPath());

... and not...

new File(uri.toString());
Notes
  1. For an android.net.Uri object which is named uri and created exactly as in the question, uri.toString() returns a String in the format "file:///mnt/sdcard/myPicture.jpg", whereas uri.getPath() returns a String in the format "/mnt/sdcard/myPicture.jpg".
  2. I understand that there are nuances to file storage in Android. My intention in this answer is to answer exactly what the questioner asked and not to get into the nuances.

Android - Convert file path to uri (not working)

Try to use this below code

 Uri uri =   Uri.fromFile(new File(filepath));

Converting file path to URI

require 'uri'

uri = URI.join('file:///', '/home/user/dir1/dir2/dir3/name.ext')
=> #<URI::Generic:0x0000000263fcc0 URL:file:/home/user/dir1/dir2/dir3/name.ext>

uri.scheme
=> "file"
uri.path
=> "/home/user/dir1/dir2/dir3/name.ext"
uri.to_s
=> "file:/home/user/dir1/dir2/dir3/name.ext"

How to convert a Java File URI inot a absolute path?

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


Related Topics



Leave a reply



Submit