前几天学习的时候遇到一个问题,Exception in thread “main” java.io.FileNotFoundException: path1 (系统找不到指定的文件。)。当时纠结了很久没有找到原因。后来通过一步步调试代码终于找到原因了。
通过类加载器获取一个工程目录中的一个文件的路径即通过方法class.getClassLoader().getResource(fileName)获取的路径时,如果该路径名有空格则获得的路径名是经过url编码后的路径。这时如果使用FileInputStream fin = new FileInputStream(“path1”);则会报错:Exception in thread “main” java.io.FileNotFoundException: path1 (系统找不到指定的文件。)。
解决办法:将class.getClassLoader().getResource(fileName)获取的路径名进行URL解码,String path2 = URLDecoder.decode(url.getPath(),”gbk”)。
Demo如下:
public class test {
public static void main(String[] args) throws DocumentException, IOException {
URL url = test.class.getClassLoader().getResource("1.xml");
//url解码
String path1 = URLDecoder.decode(url.getPath(),"gbk");
System.out.println(path1);
FileInputStream fin1 = new FileInputStream(path1);
String path2 = url.getPath();
System.out.println(path2);
FileInputStream fin2 = new FileInputStream(path2);
}
}
/D:/Users/LBX/Workspaces/MyEclipse 2015 CI/PageLogin/WebRoot/WEB-INF/classes/1.xml
/D:/Users/LBX/Workspaces/MyEclipse%202015%20CI/PageLogin/WebRoot/WEB-INF/classes/1.xml
Exception in thread "main" java.io.FileNotFoundException: D:\Users\LBX\Workspaces\MyEclipse%202015%20CI\PageLogin\WebRoot\WEB-INF\classes\1.xml (系统找不到指定的路径。)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at cn.liu.test.test.main(test.java:29)
本文介绍了在Java中通过类加载器获取文件路径时遇到的问题,当路径包含空格时,路径会被URL编码,直接使用会导致FileNotFoundException。文章提供了解决方案,即使用URLDecoder进行解码。

2114

被折叠的 条评论
为什么被折叠?



