今天遇到文件路径中有中文,读取文件就找不到,查了下得到以下解决方法,记录下来。
在使用类似这样:
- this.getClass().getClassLoader().getResource("").getPath()
来获取文件路径时,里面的路径空格会被“%20”代替,这时候如果你用这个获取到的包含“%20”的路径来new一个File时,会出现找不到路径的错误。
于是有以下官方解决方法:
- URI uri = new URI(url.toString());
- FileInputStream fis = new FileInputStream(uri.getPath())
但有另一种解决方法:
- 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);
}
}
}
}