解决spring的读取文件的工具类来获取文件等操作

今天项目又遇到了,,,读取项目下文件的情况下。 其实这个挺头疼的,,,特别是 Java web项目 下的方式和 Java 项目 下 读取文件的相对路径是有点区别的。。。所以感觉挺不好搞的。。。

而且 我们使用 第三方的 类库,工具类的时候,需要将 文件的路径给传递进去的。。。 可是 这时候 使用相对路径怎么写? 如果使用 绝对的路径又怎么写呢? 使用 非常原生的方式? 拼路径? 比如 求出 Java web的项目的当前的绝对路径,,, 或者求出当前 class 类的 根路径吗。 其实都挺不好用的。 其实我们可以是用 spring的 工具类来获取到 文件的。不用我们再次 写实现代码了。而且spring 读取文件 classpath 下面的 文件 功能还是很强大的。。。


		try {
                        // 1, 使用spring工具类 来获取文件
			File cfgFile = ResourceUtils.getFile("classpath:config/allinpay/20060400000044502.p12");
			System.out.println(cfgFile.getAbsolutePath());
			System.out.println(cfgFile.getCanonicalPath());
			System.out.println(cfgFile.getPath());
			System.out.println(cfgFile.getParent());
			System.out.println(cfgFile.getName());
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			System.out.println("文件没找到");
			e1.printStackTrace();
		}

		String bString = "";
		try {
                        //2, 获取 classpath的 根路径然后 文件的 绝对路径求出来。
			bString = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath();
			System.out.println(Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath());
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(req.getServletPath());
		System.out.println(req.getSession().getServletContext().getRealPath(""));

		File file = new File(bString + "config/allinpay/allinpay-pds.cer");
		File file2 = new File("/config/allinpay/allinpay-pds.cer");
		System.out.println(file.exists());
		System.out.println(file2.exists());

http://blog.csdn.net/loveschen/article/details/54021242

转载于:https://my.oschina.net/ouminzy/blog/1532352

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值