java.io.FileNotFoundException on an existing file

被刻印的时光 ゝ 提交于 2019-12-03 14:40:59

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

fileLocation = new String(
    Main.class.getProtectionDomain().getCodeSource().getLocation().getPath())
    .replaceAll("%20", " ");

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.

user25226

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

try { f = new File("somePath".toURI().getPath()); } catch(Exception e) {}

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.

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");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!