Last active
April 16, 2019 02:02
-
-
Save zbo2018/7771774a658870479e49aa27e3699622 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
getResource路径包含‘中文or空格’,读取文件提示找不到 | |
String path_resource = this.getClass().getClassLoader().getResource("").getPath(); | |
输出结果: | |
/E:/ideaProjects/esDemo/target/test-classes/ | |
String path = this.getClass().getResource("/demo-files/智能研发办公部张波-201903话费发票.pdf").getFile(); | |
输出结果: | |
/E:/ideaProjects/esDemo/target/test-classes/demo-files/%e6%99%ba%e8%83%bd%e7%a0%94%e5%8f%91%e5%8a%9e%e5%85%ac%e9%83%a8%e5%bc%a0%e6%b3%a2-201903%e8%af%9d%e8%b4%b9%e5%8f%91%e7%a5%a8.pdf | |
读取文件流,提示文件找不到 | |
InputStream in = new FileInputStream(path); | |
异常: | |
java.io.FileNotFoundException: E:\ideaProjects\esDemo\target\test-classes\demo-files\%e6%99%ba%e8%83%bd%e7%a0%94%e5%8f%91%e5%8a%9e%e5%85%ac%e9%83%a8%e5%bc%a0%e6%b3%a2-201903%e8%af%9d%e8%b4%b9%e5%8f%91%e7%a5%a8.pdf (系统找不到指定的文件。) | |
原因: | |
获取文件路径时,路径里面的空格会被“%20”代替。若用这个包含“%20”的路径来new一个File或读取file时,会出现找不到路径的错误。 | |
解决办法--方式1: | |
URI uri = new URI(path);//import java.net.URI; path是含有空格or中文的路径 | |
FileInputStream in = new FileInputStream(uri.getPath()); | |
解决办法--方式2: | |
String path = java.net.URLDecoder.decode(path,"utf-8");//path是含有空格or中文的路径 | |
InputStream in = new FileInputStream(path); | |
解决办法--方式3: | |
String path_uri = this.getClass().getResource("/demo-files/智能研发办公部张波-201903话费发票.pdf").toURI().getPath(); | |
InputStream in = new FileInputStream(path_uri); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Junit下获取src/test/resource路径 | |
String rootPath=this.getClass().getResource("/a.txt").getFile().toString(); | |
System.out.println(rootPath); | |
String rootPath1 = this.getClass().getResource("/a.txt").toString(); | |
System.out.println(rootPath1); | |
String rootPath2 = this.getClass().getResource("/").toString(); | |
System.out.println(rootPath2); | |
String rootPath3 = this.getClass().getResource("").toString(); | |
System.out.println(rootPath3); | |
输出结果: | |
/E:/ideaProjects/esDemo/target/test-classes/a.txt | |
file:/E:/ideaProjects/esDemo/target/test-classes/a.txt | |
file:/E:/ideaProjects/esDemo/target/test-classes/ | |
file:/E:/ideaProjects/esDemo/target/test-classes/com/zbo/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment