getResource中文或有空格路径处理

今天遇到文件路径中有中文,读取文件就找不到,查了下得到以下解决方法,记录下来。


在使用类似这样:

 

Java代码   收藏代码
  1. this.getClass().getClassLoader().getResource("").getPath()  

  来获取文件路径时,里面的路径空格会被“%20”代替,这时候如果你用这个获取到的包含“%20”的路径来new一个File时,会出现找不到路径的错误。

于是有以下官方解决方法:

 

Java代码   收藏代码
  1. URI uri = new URI(url.toString());  
  2. FileInputStream fis = new FileInputStream(uri.getPath())  

 

但有另一种解决方法:

 

Java代码   收藏代码
  1. 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);
				}
			}
		}
	}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值