getResource中文或有空格路径处理
2014-07-12 16:09
183 查看
今天遇到文件路径中有中文,读取文件就找不到,查了下得到以下解决方法,记录下来。
在使用类似这样:
Java代码
this.getClass().getClassLoader().getResource("").getPath()
来获取文件路径时,里面的路径空格会被“%20”代替,这时候如果你用这个获取到的包含“%20”的路径来new一个File时,会出现找不到路径的错误。
于是有以下官方解决方法:
Java代码
URI uri = new URI(url.toString());
FileInputStream fis = new FileInputStream(uri.getPath())
但有另一种解决方法:
Java代码
configPath = java.net.URLDecoder.decode(configPath,"utf-8");
于是乎,问题解决了……
在项目中遇到的实践如下:
在使用类似这样:
Java代码
this.getClass().getClassLoader().getResource("").getPath()
来获取文件路径时,里面的路径空格会被“%20”代替,这时候如果你用这个获取到的包含“%20”的路径来new一个File时,会出现找不到路径的错误。
于是有以下官方解决方法:
Java代码
URI uri = new URI(url.toString());
FileInputStream fis = new FileInputStream(uri.getPath())
但有另一种解决方法:
Java代码
configPath = java.net.URLDecoder.decode(configPath,"utf-8");
于是乎,问题解决了……
在项目中遇到的实践如下:
String sql_file=this.getClass().getResource("").getPath(); /* * 方法一 * try { //解决获取路径中文用%转义 sql_file = java.net.URLDecoder.decode(sql_file,"utf-8"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } */ //方法二(官网解决方式) try { URI uri = new URI(sql_file.toString()); sql_file =uri.getPath(); } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } sql_file = sql_file.substring(0, sql_file.length()-23)+"/sql/"; File file = new File(sql_file); File[] files = file.listFiles(); if (files != null) { for (File f : files) { String type = f.getPath().substring( f.getPath().length()-3, f.getPath().length()); if ("sql".equals(type)) { InputStream is = null; try { is = new FileInputStream(f); } catch (FileNotFoundException e) { e.printStackTrace(); } InputStreamReader isreader = new InputStreamReader(is); BufferedReader reader = new BufferedReader(isreader); read(reader); } } } }
相关文章推荐
- getResource中文或有空格路径处理
- getResource中文或有空格路径处理
- getResource中文或有空格路径处理
- getResource中文或有空格路径处理
- getResource中文或有空格路径处理
- this.getClass().getClassLoader().getResource("")遇到有中文路径的解决方法
- java 读取文件路径中空格和中文的处理
- getPath()返回路径包含的“%20”(空格)的处理
- 利用getClassLoader().getResource(*).getPath()获取绝对路径时,因为空格不能获取绝对路径的问题
- Java文件路径空格及中文处理
- class.getResource("XXX").getPath()返回路径空格变成了 异常解决
- java 读取文件路径空格和中文的处理
- java 读取文件路径空格和中文的处理
- class.getResource.getPath()中文空格转义问题
- java 路径 批处理空格 getRuntime().exec 空格解决办法
- getResource().getPath() 路径带空格问题
- java 读取文件路径空格和中文的处理
- log4j用于读取.xml文件的出现了错误,类加载器.getResource("user.xml").getPath()返回路径空格变成了%20
- java学习笔记:getPath取路径文件夹中有空格的处理方法
- java 读取文件路径空格和中文的处理