Convert windows path to URI in Java? [duplicate] - java

This question already has answers here:
Java: Get URI from FilePath
(5 answers)
Closed 7 years ago.
What is in Java the correct way to create a file URI for Windows? I tried
new URI("file", null, file.getAbsolutePath(), null);
but this complains about a relative path used in an absolute URI. I also tried prefixing the path with "//", but this makes 'c:' into a hostname. Then I prefixed the path with "////". A subsequent uri.getPath() then has a leading "//", which still does not seem right.
Is there any clean way to go from file.getAbsolutePath() to a URI with file:// protocol and back to a Windows path usable for new File(...) on Windows?

check File class docs. it provide toURI() method. below code seemed give output:
File file = new File("d:/myfolder/myfile.txt");
System.out.println(file.toURI());

Related

How to convert network path to URL in Java

I have literally searched the whole internet for this question but I have not found an answer. I have a file, in the network and I want to create an Itext image with it and for that, I have to convert its path to URL. The problem is when I use path.toURI().toURL() it appends my project path to the URL such that my URL ends up starting with C:/ which will not work.
Is there a way to just convert a string to file URL in java?
I have tried this:
String paths = "‪\\\\DESKTOP-A11F076\\Users\\Benson Korir\\Desktop\\walgotech\\passport.jpg";
String first = "file:" + paths.replaceAll("\\\\", "//").replaceAll("////", "//");
String second = "file://desktop-a11f076//Users//Benson Korir//Desktop//walgotech//passport.jpg";
System.out.println(first);
System.out.println(second);
The second string I have copied directly from the browser and it works fine. Funny this is these two strings output the same thing but the first string brings an error when I use it here:
Image image1 = Image.getInstance(second);
I am getting the error below:
java.io.FileNotFoundException: ‪\DESKTOP-A11F076\Users\Benson Korir\Desktop\walgotech\passport.jpg (The system cannot find the path specified)
If I got your requirement correctly, your path is a UNC file name, and that is the short form of an SMB path, with DESKTOP-A11F076 being the remote machine, and \Users\Benson Korir\Desktop\walgotech\passport.jpg being the path to the file on that machine.
If I am correct with that assumption, my understanding is that your URL have to look like this: smb://‪DESKTOP-A11F076/Users/Benson Korir/Desktop/walgotech/passport.jpg.
As far I remember is a Java java.io.File object capable to handle a UNC file name (this article implies that, too), but when translating it to a URI, it tries to make it absolute first, and there it fails in your case.
I usually avoid working on Windows whenever possible, therefore I have no environment to verify that.

Getting the full path of parent directory [java] [duplicate]

This question already has answers here:
How to get just the parent directory name of a specific file
(10 answers)
Closed 4 years ago.
It should be rather easy, but I could not find a clean way to do so. I'm trying to get the parent full path of parent directory in a path. Consider the following path: /bin/src/config/file, I would like to get /bin/src/config in Java. So I get a string and need to get the full path (absolute path, not just the name and not relative) of the parent directory. What is the cleanest way to do so?
You can use this, which will print the folder your file is in where fileName is your filename:
Path f = Paths.get(fileName);
System.out.println(f.getParent());
Eg for String fileName = "C:\\Users\\Me\\Documents\\video.html" the output is C:\Users\Me\Documents.

gwt servlet getRessourceAsStream always returns null [duplicate]

This question already has answers here:
getResourceAsStream returns null
(26 answers)
Closed 6 years ago.
I have this peace of code to load a text file inside of a servlet:
String lFileName = mServletContext.getRealPath(mFile);
InputStream lInputStream = mServletContext.getResourceAsStream(lFileName);
InputStream lInputStream2 = mServletContext.getResourceAsStream(mFile);
Both InputStream's are null. I have absolutly no idear why.
The value of mFile is "file.txt".
The value of lFile is "C:\development\workspace\MyGwtApp\war\file.txt".
if I navigate with my explorer to that directory the file file.txt is in it...!
I test my gwt application with the super dev mode.
Compile the gwt app runs without problems.
Do you see the problem?
getResourceAsStream definition
Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object's class loader.
This means that you can read mFile if it exists in your classpath like under WEB-INF/classes. So place your file in your src directory where your java classes exists and look if the file comes to the classes directory and just use its name to get it as resource. Example: filename = "file.txt"

Obtain path to file with filename [duplicate]

This question already has answers here:
Get path of Android resource
(3 answers)
How can I write a Drawable resource to a File?
(2 answers)
Closed 8 years ago.
I am writing an Android app and I need to do something I would consider incredibly simple, yet am having the hardest time figuring out.
How can I obtain the path to a JPG file so that I can upload it to a server?
The file is snoopy.jpg and is in the res/drawable folder
I've tried:
File sourceFile = new File("android.resource://com.appname.something/drawable/snoopy");
But, that's not a file
I've tried:
File sourceFile = new File("drawable/snoopy");
and that doesn't work.
I tried putting snoopy.jpg in the root of the app directory and attempting:
File sourceFile = new File("/snoopy.jpg");
And that still didn't work.
Any help would be greatly appreciated!
Try this :
InputStream is = getResources().openRawResource(R.drawable.snoopy);
You can open an InputStream from your drawable resource using the above code. Also, before doing any file operation, you need to check if file.exist() and if it returns false then you need to create a file via f.createNewFile();

Convert URL to normal windows filename Java

Is there a way to convert this:
/C:/Users/David/Dropbox/My%20Programs/Java/Test/bin/myJar.jar
into this?:
C:\Users\David\Dropbox\My Programs\Java\Test\bin\myJar.jar
I am using the following code, which will return the full path of the .JAR archive, or the /bin directory.
fullPath = new String(MainInterface.class.getProtectionDomain()
.getCodeSource().getLocation().getPath());
The problem is, getLocation() returns a URL and I need a normal windows filename.
I have tried adding the following after getLocation():
toString() and toExternalForm() both return:
file:/C:/Users/David/Dropbox/My%20Programs/Java/Test/bin/
getPath() returns:
/C:/Users/David/Dropbox/My%20Programs/Java/Test/bin/
Note the %20 which should be converted to space.
Is there a quick and easy way of doing this?
The current recommendation (with JDK 1.7+) is to convert URL → URI → Path. So to convert a URL to File, you would say Paths.get(url.toURI()).toFile(). If you can’t use JDK 1.7 yet, I would recommend new File(URI.getSchemeSpecificPart()).
Converting file → URI: First I’ll show you some examples of what URIs you are likely to get in Java.
-classpath URLClassLoader File.toURI() Path.toUri()
C:\Program Files file:/C:/Program%20Files/ file:/C:/Program%20Files/ file:///C:/Program%20Files/
C:\main.c++ file:/C:/main.c++ file:/C:/main.c++ file:///C:/main.c++
\\VBOXSVR\Downloads file://VBOXSVR/Downloads/ file:////VBOXSVR/Downloads/ file://VBOXSVR/Downloads/
C:\Résume.txt file:/C:/R%c3%a9sume.txt file:/C:/Résume.txt file:///C:/Résume.txt
\\?\C:\Windows (non-path) file://%3f/C:/Windows/ file:////%3F/C:/Windows/ InvalidPathException
Some observations about these URIs:
The URI specifications are RFC 1738: URL, superseded by RFC 2396: URI, superseded by RFC 3986: URI. (The WHATWG also has a URI spec, but it does not specify how file URIs should be interpreted.) Any reserved characters within the path are percent-quoted, and non-ascii characters in a URI are percent-quoted when you call URI.toASCIIString().
File.toURI() is worse than Path.toUri() because File.toURI() returns an unusual non-RFC 1738 URI (gives file:/ instead of file:///) and does not format URIs for UNC paths according to Microsoft’s preferred format. None of these UNC URIs work in Firefox though (Firefox requires file://///).
Path is more strict than File; you cannot construct an invalid Path from “\.\” prefix. “These prefixes are not used as part of the path itself,” but they can be passed to Win32 APIs.
Converting URI → file: Let’s try converting the preceding examples to files:
new File(URI) Paths.get(URI) new File(URI.getSchemeSpecificPart())
file:///C:/Program%20Files C:\Program Files C:\Program Files C:\Program Files
file:/C:/Program%20Files C:\Program Files C:\Program Files C:\Program Files
file:///C:/main.c++ C:\main.c++ C:\main.c++ C:\main.c++
file://VBOXSVR/Downloads/ IllegalArgumentException \\VBOXSVR\Downloads\ \\VBOXSVR\Downloads
file:////VBOXSVR/Downloads/ \\VBOXSVR\Downloads \\VBOXSVR\Downloads\ \\VBOXSVR\Downloads
file://///VBOXSVR/Downloads \\VBOXSVR\Downloads \\VBOXSVR\Downloads\ \\VBOXSVR\Downloads
file://%3f/C:/Windows/ IllegalArgumentException IllegalArgumentException \\?\C:\Windows
file:////%3F/C:/Windows/ \\?\C:\Windows InvalidPathException \\?\C:\Windows
Again, using Paths.get(URI) is preferred over new File(URI), because Path is able to handle the UNC URI and reject invalid paths with the \?\ prefix. But if you can’t use Java 1.7, say new File(URI.getSchemeSpecificPart()) instead.
By the way, do not use URLDecoder to decode a file URL. For files containing “+” such as “file:///C:/main.c++”, URLDecoder will turn it into “C:\main.c  ”! URLDecoder is only for parsing application/x-www-form-urlencoded HTML form submissions within a URI’s query (param=value&param=value), not for unquoting a URI’s path.
2014-09: edited to add examples.
String path = "/c:/foo%20bar/baz.jpg";
path = URLDecoder.decode(path, "utf-8");
path = new File(path).getPath();
System.out.println(path); // prints: c:\foo bar\baz.jpg
The current answers seem fishy to me.
java.net.URL.getFile
turns a file URL such as this
java.net.URL = file:/C:/some/resource.txt
into this
java.lang.String = /C:/some/resource.txt
so you can use this constructor
new File(url.getFile)
to give you the Windows path
java.io.File = C:\some\resource.txt
As was mentioned - getLocation() returns an URL. File can easily convert an URI to a path so for me the simpliest way is just use:
File fullPath = new File(MainInterface.class.getProtectionDomain().
getCodeSource().getLocation().toURI());
Of course if you really need String, just modify to:
String fullPath = new File(MainInterface.class.getProtectionDomain().
getCodeSource().getLocation().toURI()).toString();
You don't need URLDecoder at all.
The following code is what you need:
String path = URLDecoder.decode("/C:/Users/David/Dropbox/My%20Programs/Java/Test/bin/", "UTF-8");
System.out.println(new File(path).getPath());
Hello confused people from the future. There is a nuance to the file path configuration here. The path you are setting for TESSDATA_PREFIX is used internally by the C++ tesseract program, not by the java wrapper. This means that if you're using windows you will need to replace the leading slash and replace all other forward slashes with backslashes. A very hacky workaround looks like this:
URL pathUrl = this.getClass().getResource(TESS_DATA_PATH);
String pathStr = pathUrl.getPath();
// hack to get around windows using \ instead of /
if (SystemUtils.IS_OS_WINDOWS) {
pathStr = pathStr.substring(1);
pathStr = pathStr.replaceAll("/", "\\\\");
}

Categories