File protocol schema - java

I have path to local directory:
String myPath = "C:\install";
I need to pass this path to method in third-party library. Third-party use path to directory in following ways:
File f = new File(s);
URL u = f.toURL();
and
new MyObject("file://" + myPath);
If it simply "C:\install", then I get exception while executing second pice of code (MyObject) - there is only 2 slashes instead 3. But if I add one slash to beginning of the string: "\C:\install", then second pice of code executes correctly, but File#toURL(); converts it to file:/C:/install - i.e. it ignores slash at the beginning..

Related

Is there a way to get the path of a File with "/" instead of "\"?

I am making an HTTP Server in Java so that (on start) it finds all files in a directory (and it's sub-directories) and adds them to the server. But when getting the path of a file and trying to give it to HttpServer.createContext(), it throws a java.lang.IllegalArgumentException: Illegal value for path or protocol. (with the string argument, say "\folder/index.html"). To get this value, I used
file.getParent().substring(24) + "/" + file.getName()
I used substring because I had to exclude the folder the web server is in. The illegal character is the backslash. I have tried extending File to change separator and separatorChar, but that only created 2 new variables. While using String.replace() didn't seem to have any effect. Is there a different method than File.getParent or File.getPath that I can use, or is there a way to use String.replace that I am not seeing?
EDIT:
String.replace() seems to be the best answer... But I am not completely sure how to use it.
EDIT 2: For some reason the backslash isn't showing up, so I changed it.
You have to use the java System.getProperty.
Notice that, in this context, "file.separator" is a key which we are
using to get this property from current system executing the java VM.
Insteady of using a slash (/), you should choose a platform agnostic file separator, as an example it should be:
String separator = System.getProperty("file.separator");
System.out.println(separator);
// unix / , windows \
Have a look at Paths.get(...)
Try Paths.get(".") // current working directory.
Or tell it, on which path it should start:
Use System.getProperty("user.dir"), for current loged in user, home directory.
String pathStr = "/";
Path homeDir = Paths.get(System.getProperty("user.dir"))
Getting from the user directory into the data directory: homeDir.get("data")
Path dataPath = Paths.get(System.getProperty("user.dir"));
File dataFile = dataPath.toFile();
Now use operations on dataFile, to check what files and directories there are, on that location of the file system.

Java - find jar file of class (or classes directory)

I can request the URL for the jar file or classes directory where Java loaded a class from:
Class clazz = ...
URL url = clazz.getProtectionDomain().getCodeSource().getLocation();
but how to correctly convert this to a File (or Path) - especially with respect to some characters of the path escaped in URLs? I've tried this:
String fileName = URLDecoder.decode(url.getFile(), "UTF-8");
File jarFileOrClassesDir = new File(fileName);
but this causes problems if there is a + inside the path (the + is replaced with a space).
but this causes problems if there is a + inside the path (the + is replaced with a space).
This is standar behavior of URLDecoder. See more information at JavaDoc [1], plus (+) is mentioned there as well.
Solution using Paths
Using Paths#get(URI) [2] should preserve all "special" symbols and you can pass directly URI which can be retrieved directly from URL using URL#toURI() [3].
So in summary:
final var filePath = Paths.get(url.toURI()); // We can extract any information from Path e.g. fileName.
shoud work as expected.
[1] https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/net/URLDecoder.html
[2] https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Paths.html#get(java.net.URI)
[3] https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/net/URL.html#toURI()

Directory and Filename Concatenating does NOT work

I am working in Netbeans IDE.
What I want to do is:
Get The directory of the Current Java Application (Ex: "F:\PadhooWorld")
Join a file name to it. (Ex: "\Somestuff.txt")
Check if that File exists (Ex: "F:\PadhooWorld\Somestuff.txt")
Do a if.. else activity
When I tam trying to Join Directory + Filename, it is throwing lots of error messages like Path cannot be converted to string etc . Searching the net the whole day, doesn't yield any simple usable solution
Please specify a very simple solution.
EDIT
I have only 2 lines of code as yet
String AppPath = System.getProperty("user.dir");
String fullPath = AppPath + "\Surabhi.txt";
The First Line resolves alright
The Second line (I tried different variations) No Luck. It is underlined in red. Error hints say stuffs like 'Path cannot be converted to string'..
I cannot RUN the code.
It sounds like you're overthinking it. You can just create a File object with the file name you want (the path to the current directory will be used by default) and then call exists() on it:
File f = new File("filename.txt");
System.out.println(f.getAbsolutePath()); //Just for debug if you want to check the path
if(f.exists()) {
//Whatever
}
Alternatively, if you want to specify the path as well as the file name:
String AppPath = System.getProperty("user.dir");
String fileName = "Surabhi.txt";
File f = new File(AppPath, fileName); //f.getAbsolutePath() will give the concatenated name
if(f.exists()) {
//Whatever
}

NullPointerException on an existing path

I get a problem while creating a Classifier. My existing path to it causes a NullPointerException. I am working with OpenCV 2.4.11 in Eclipse. The OS is Windows that's why I added another backslash between folders. When I insert the path with single backslashes in a file explorer it opens the XML File correctly. My code looks like this:
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
System.out.println("\nRunning FaceDetector");
String path = "C:\\Users\\Juergen\\OpenCV\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml";
System.out.println("path:" + path);
CascadeClassifier faceDetector = new CascadeClassifier(FaceDetector.class.getResource(path).getPath());
The output is:
Running FaceDetector
path:C:\Users\Juergen\OpenCV\opencv\sources\data\haarcascades\haarcascade_frontalface_alt.xml
Exception in thread "main" java.lang.NullPointerException
at FaceDetector.main(FaceDetector.java:24)
The code is based on the following instruction.
Any ideas on why the NullPointerException is thrown are appreciated.
Thanks
When we look at the Java API wi find this:
https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResource-java.lang.String-
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Therefore you must add a '/' in front of your absolute path:
String path = "/C:\\Users\\Juergen\\OpenCV\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml";
And you also should get rid of the windows file separator. Java understands the unix file separator and knows how to handle that on a windows system:
String path = "/C:/Users/Juergen/OpenCV/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml";
I replaced my string by Yours, nothing changed. Still get a NullPointerException. The check
if (!new File(path).exists()) { throw new FileNotFoundException("Yikes!");}
does not throw any Exception – Jürgen K
Then from the *.class.getResource(path) you get an URL and from the URL's getPath() method you get a String which should most likely be the same as your original string.
Did you try to use it directly (with the leading '/')?

File.mkdir is not working and I can't understand why

I've this brief snippet:
String target = baseFolder.toString() + entryName;
target = target.substring(0, target.length() - 1);
File targetdir = new File(target);
if (!targetdir.mkdirs()) {
throw new Exception("Errore nell'estrazione del file zip");
}
doesn't mattere if I leave the last char (that is usually a slash). It's done this way to work on both unix and windows. The path is actually obtained from the URI of the base folder. As you can see from baseFolder.toString() (baseFolder is of type URI and is correct). The base folder actually exists. I can't debug this because all I get is true or false from mkdir, no other explanations.The weird thing is that baseFolder is created as well with mkdir and in that case it works.
Now I'm under windows.
the value of target just before the creation of targetdir is "file:/C:/Users/dario/jCommesse/jCommesseDB"
if I cut and paste it (without the last entry) in windows explore it works...
The path you provide is not a file path, but a URI.
I suggest you try the following :
URI uri = new URI("file://c:/foo/bar");
File f = new File(uri).
It looks, to me, as if the "file:/" at the beginning is the problem... Try getAbsolutePath() instead of toString().
The File constructor taking a String expects a path name. A path name is not an URI.
Remove the file:/ from the front of the String (or better yet, use getPath() instead of toString()) to get to the path you need.

Categories

Resources