Coded path from getResource() doesn't work - java

I'm trying to get this folder
File imagesOrg = new File(getClass().getResource("/stock").getPath());
I've printed it out in console with
System.out.println(imagesOrg.getAbsolutePath());
and there is a space within my path so it was changed to %20 and because of that the rest of my code doesn't work which is:
for(final File child : imagesOrg.listFiles()) {
System.out.println(child.getName());
}
If I put the whole path in new File with a space instead of %20 it works fine is there an easy solution to this?

I recommand URL decoder.
You can use like this..
String result = java.net.URLDecoder.decode(url, "UTF-8");

Related

FileNotFoundException while trying to open a File

I am trying to d file = new file (location) while location of file is absolute path with somethign like this : \\test\hold\REPO/TEST/Letter/123.pdf
I am getting file not found exception while files are there in this path. what could be going wrong? can i have path with both forward and backward slash?
String separator = System.getProperty("file.separator");
So location can be rewritten to
location=separator+"test"+separator+"hold"+separator +"REPO"+separator "TEST"+separator+"Letter"+separator+"123.pdf";
In this case no need to think about underlying OS
You need two slashes in a string literal to represent one in the filename. Try
"\\\\test\\hold\\REPO/TEST/Letter/123.pdf"
or better still
"//test/hold/REPO/TEST/Letter/123.pdf"
There is never a need to use a backslash in a filename in Java.
Try adding quotes around the filename.
You can write your code without single backward slashes.if you want to use back-word slashes use \\ instead of \ .A single backward slashes create a problem if you put it inside the String literal.So you can write you code in multiple ways to avoid your exceptions.
1) File f=new File("\\test/hold/REPO/TEST/Letter/123.pdf");
2) File f=new File("\\test\\hold\\REPO/TEST/Letter/123.pdf");
3) File f=new File("\\test\\hold\\REPO\\TEST\\Letter\\123.pdf");
4) File f=new File("/test/hold/REPO/TEST/Letter/123.pdf");
you can use :-
InputStream input = new URL("\\test\hold\REPO/TEST/Letter/123.pdf").openStream();
or
File file = new File(location);
where location=\\test\hold\REPO/TEST/Letter/123.pdf; and Check Using SOP statement whether URL is Call properly or not . hope it will help you to fine better solution

Set java.security.policy property to a cross-platform file path

I'm trying to set the system property "java.security.policy" programmatically.
It works, as long as the path to the security policy file has no spaces.
File myFileReference = new File("C:\folder_name\security.policy")
System.setProperty("java.security.policy", myFileReference.getAbsolutePath());
System.setSecurityManager(new RMISecurityManager());
If there are spaces int the file path, they get escaped with a %20, like this
"C:\folder%20name\security.policy".
The code above executes fine, but then all security checks fail. I assume setProperty doesn't really find the file.
On Windows, writing the file name without that escaping for spaces works.
System.setProperty("java.security.policy", "C:\\some folder\\wideopen.policy");
So, the problem seems to be that %20 space escaping. I could replace it using a regex, but maybe that would make it work just on Windows, and fails somewhere else.
Also, I don't want to hard-code the file path like that.
I looked at the Java doc for a File function that returns a "System.setProperty" compatible path name that works on any platform. I also tried things like toURI().toString(), to no avail.
Is there an elegant way to get a working file path String from a File reference in 1 line of code?
EDIT:
This was simplified code, I construct the file like this
URL policyURL = Class.class.getResource("/sub local folder/wideopen.policy");
new File(policyURL.getFile())
I needed a relative path, so I used that little getResource trick, which happens to return an URL, with the nasty %20 escapings.
I can use an URLDecoder to strip them away now that I know what the problem is.
But is there a less error prone way?
I solved using the URLDecoder class. Here is a complete example of what I was trying to do, and the solution that made it work.
//here is the trick
URL policyFileURL = Class.class.getResource("/server/model/easy.policy");
String policyFilePath = "";
try {
policyFilePath = URLDecoder.decode(policyFileURL.getFile(), "UTF-8");
}
catch (UnsupportedEncodingException e) {}
//here what I wanted to do (now it works)
server.activate(port, new File(policyFilePath));

java.io.FileNotFoundException on an existing file

I am getting this error when I try to open a file:
java.io.FileNotFoundException: D:\Portable%20Programs\Android%20Development\workspace3\XXX-desktop\bin\World_X.fr (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
The file is existing in the directory but I am still getting this error. However when I copy the same file in the Eclipse workspace Project src folder, no such Exception is returned (though this method also creates the World_X.fr file in the bin folder).
What I am actually trying to do is get the absolute location of the .jar file through this:
fileLocation = new String(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath());
And then I am appending "World_X.fr" to the fileLocation string but this is not working. Please help me in this regard.
The preferred way to convert a file: URL into an actual File is this:
File file = new File(url.toURI());
This takes care of all checks and quoting/escaping.
Using getPath() instead will leave these odd bits up to you.
You need to unescape the %20 to spaces. e.g.:
fileLocation = new String(
Main.class.getProtectionDomain().getCodeSource().getLocation().getPath())
.replaceAll("%20", " ");
Here is the solution for that , this will work only after JDK1.5 ,
try { f = new File("somePath".toURI().getPath()); } catch(Exception e) {}
The confirmed solution is quite old and even though it works for this particular case it is far more convenient to use URLDecoder, because %20 is only one encoded character, but in your path there can be whole lot of different encoded characters.
fileLocation = URLDecoder.decode(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath(), "UTF-8");
Try leaving out the %20, and use normal spaces instead. Also, you're using backslashes, in your code if you're using backslashes make sure you escape them first.

Java - Clean file path

I want to clean the path I use in my App. The path can be modified and sometimes I got something like that:
C:/users/Username/Desktop/\..\..\..\Windows\Web\..\..\Program Files\..\Program Files\..\Python27\
But I would like to have something like:
C:\Python27\
That's an example!
How can I clean the path to get only the necessary part?
Thanks.
If fileName is your filename string, then something like:
String cleanedFilename = new File(fileName).getCanonicalPath();
should do it...
Se also the API description.
Here is the code I have just tried.
new File("c:/temp/..").getCanonicalPath();
It returns 'C:\', that is right. The parent of c:/temp is indeed c:\
You could try using the File.getCanonicalPath() method:
File file = new File("my/init/path");
String path = file.getCanonicalPath();
I haven't test though, tell us back!
EDIT:
#MathiasSchwarz is right, use getCanonicalPath() instead of getAbsolutePath() (link)

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