java.io.FileNotFoundException on an existing file
Asked Answered
U

5

9

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.

Unfreeze answered 19/7, 2012 at 16:55 Comment(2)
Do you really have paths with "%20" in them?Atlantean
@DanielDiPaolo yeah somehow! I am sleeping...... :)Unfreeze
G
11

You need to unescape the %20 to spaces. e.g.:

fileLocation = new String(
    Main.class.getProtectionDomain().getCodeSource().getLocation().getPath())
    .replaceAll("%20", " ");
Granadilla answered 19/7, 2012 at 16:57 Comment(0)
L
23

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.

Longsuffering answered 19/7, 2012 at 17:58 Comment(0)
G
11

You need to unescape the %20 to spaces. e.g.:

fileLocation = new String(
    Main.class.getProtectionDomain().getCodeSource().getLocation().getPath())
    .replaceAll("%20", " ");
Granadilla answered 19/7, 2012 at 16:57 Comment(0)
A
6

Here is the solution for that , this will work only after JDK1.5 ,

try { f = new File("somePath".toURI().getPath()); } catch(Exception e) {}
Archenteron answered 24/5, 2013 at 6:48 Comment(0)
M
1

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");
Mcmichael answered 30/4, 2018 at 11:21 Comment(0)
F
0

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.

Fowle answered 19/7, 2012 at 16:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.