loading network path in java code - java

I'm loading some network path in my java code. It is not taking the same format as present in the configuration file, missing one slash.
Example:
String path = "//abckatte.com/abc/test";
File fileobj = new File(path);
Whenever I saw the fileobj in log message it is displaying as /abckatte.com/abc/test. One slash is missing.
I tried with appending two more slash like.
String path = "////abckatte.com/abc/test";
then also it is not working.

You could make use of Apache Commons VFS 2, as it provides access to several file systems. Chek it out here, in Local files file://///somehost/someshare/afile.txt.

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.

Convert URL to normal windows filename Java 6

I am trying to read package name from a jar file. My probem is that when I get URL, it contains unrecognized form to be recognized by windows file.
I read this solution. But this did not helped me. Convert URL to normal windows filename Java.
directoryURL.toURI().getSchemeSpecificPart() does not convert windows style.
This is my code.
// Get a File object for the package
URL directoryURL = Thread.currentThread().getContextClassLoader()
.getResource(packageNameSlashed);
logger.info("URI" + directoryURL.toURI());
logger.info("Windows file Name" + directoryURL.toURI().getSchemeSpecificPart());
// build jar file name, then loop through zipped entries
jarFileName = URLDecoder.decode(directoryURL.getFile(), "UTF-8");
jarFileName = jarFileName.substring(0, jarFileName.indexOf(".jar"));
// HERE Throws exception"
jf = new JarFile(jarFileName + ".jar");
while (jarEntries.hasMoreElements()) {
entryName = jarEntries.nextElement().getName();
logger.info("Entry name: " + entryName);
if (entryName.startsWith(packageNameSlashed)
&& entryName.length() > packageNameSlashed.length() + 5
&& entryName.endsWith(".class")) {
entryName = entryName.substring(packageNameSlashed.length() + 1);
packageClassNames.put(entryName, packageName);
}
}
This is log.
16-02-2015 14:02:15 INFO - URI jar:file:/C:/SVN/AAA/trunk/aaa/client/target/server-1.0.jar!/packageName
16-02-2015 14:02:15 INFO Windows file Name file:/C:/SVN/AAA/trunk/aaa/client/target/server-1.0.jar!/packageName
A "jar:..." URL does not identify a file. Rather, it identifies a member of a JAR file.
The syntax is (roughly speaking) "jar:<jar-url>!<path-within-jar>", where the is itself a URL; e.g. a "file:" URL in your example.
If you are going to open the JAR file and iterate entries like that, you need to:
Extract the schemeSpecificPart of the original URL
Split the schemeSpecificPart on the "!" character.
Parse the part before the "!" as a URI, then use File(URI) to get the File.
Use the File to open the ZipFile.
Lookup the part after the "!" in the ZipFile ...
The answer by Stephen has all the elements you need.
With the getResource(package).getURI() or getResoucer(package).toFile you are getting the path to the resource.
Do substring on it to extract the part between file:// and ! this is the path to physical location of your jar of interest.
De new File on this sub-path and you have handle to your jar.
Jar is normal zip file, and process it as such (java.util.zip and there are manuals on the web).
List content of your zip file (now you may need to navigate using the bits behind ! sign in your original path), and you get your classes name.
I am not sure if this is the best way to achieve your goal, I would check how classes discovery (which is what you are trying to do, are implemented in some open source framework (for example tomcat uses it, JPA impelementation to find the entitities). There is also discovery project on apache but it seems to be dead for a while.

File class cannot access file using absolute path

I am trying to access a file using the file class but it works only with below code
File file = new File("s:\\testing\\selenium\\Version8\\locators\\OR.properties");
however I need to use this approach where I go directly to the server:
"\\GIGABYTE\\s-drive\\Testing\\selenium\\Version8\\locators\OR.properties"in which the above will not find the file - very strange
Any clue as to why this is?
To go directly to the server you will need to have 4 slashes as two are actual slashes and 2 are escape characters:
\\\\GIGABYTE\\s-drive\\Testing\\selenium\\Version8\\locators\OR.properties
You can try the below code:
File file = new File("\\\\GIGABYTE\\s-drive\\Testing\\selenium\\Version8\\locators\\OR.properties");
or this:
File file = new File("//GIGABYTE/s-drive/Testing/selenium/Version8/locators/OR.properties");

Files, URIs, and URLs conflicting in Java

I am getting some strange behavior when trying to convert between Files and URLs, particularly when a file/path has spaces in its name. Is there any safe way to convert between the two?
My program has a file saving functionality where the actual "Save" operation is delegated to an outside library that requires a URL as a parameter. However, I also want the user to be able to pick which file to save to. The issue is that when converting between File and URL (using URI), spaces show up as "%20" and mess up various operations. Consider the following code:
//...user has selected file
File userFile = myFileChooser.getSelectedFile();
URL userURL = userFile.toURI().toURL();
System.out.println(userFile.getPath());
System.out.println(userURL);
File myFile = new File(userURL.getFile());
System.out.println(myFile.equals(userFile);
This will return false (due to the "%20" symbols), and is causing significant issues in my program because Files and URLs are handed off and often operations have to be performed with them (like getting parent/subdirectories). Is there a way to make File/URL handling safe for paths with whitespace?
P.S. Everything works fine if my paths have no spaces in them (and the paths look equal), but that is a user restriction I cannot impose.
The problem is that you use URL to construct the second file:
File myFile = new File(userURL.getFile());
If you stick to the URI, you are better off:
URI userURI = userFile.toURI();
URL userURL = userURI.toURL();
...
File myFile = new File(userURI);
or
File myFile = new File( userURL.toURI() );
Both ways worked for me, when testing file names with blanks.
Use instead..
System.out.println(myFile.toURI().toURL().equals(userURL);
That should return true.

Reading File In JAR using Relative Path

I have some text configuration file that need to be read by my program. My current code is:
protected File getConfigFile() {
URL url = getClass().getResource("wof.txt");
return new File(url.getFile().replaceAll("%20", " "));
}
This works when I run it locally in eclipse, though I did have to do that hack to deal with the space in the path name. The config file is in the same package as the method above. However, when I export the application as a jar I am having problems with it. The jar exists on a shared, mapped network drive Z:. When I run the application from command line I get this error:
java.io.FileNotFoundException: file:\Z:\apps\jar\apps.jar!\vp\fsm\configs\wof.txt
How can I get this working? I just want to tell java to read a file in the same directory as the current class.
Thanks,
Jonah
When the file is inside a jar, you can't use the File class to represent it, since it is a jar: URI. Instead, the URL class itself already gives you with openStream() the possibility to read the contents.
Or you can shortcut this by using getResourceAsStream() instead of getResource().
To get a BufferedReader (which is easier to use, as it has a readLine() method), use the usual stream-wrapping:
InputStream configStream = getClass().getResourceAsStream("wof.txt");
BufferedReader configReader = new BufferedReader(new InputStreamReader(configStream, "UTF-8"));
Instead of "UTF-8" use the encoding actually used by the file (i.e. which you used in the editor).
Another point: Even if you only have file: URIs, you should not do the URL to File-conversion yourself, instead use new File(url.toURI()). This works for other problematic characters as well.

Categories