通过Class类反射获取项目中的文件路径

针对web项目包中的文件发布到服务器上无法读取问题,特采用类反射机制获取文件的绝对路径。
InputStream fis = PropertiesUtil.class.getClassLoader().getResourceAsStream(filePath);
            //从输入流中读取属性列表(键和元素对)
            prop.load(fis);
            //调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。
            //强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
            String a=PropertiesUtil.class.getClassLoader().toString();
            System.out.println(a);
            OutputStream fos = new FileOutputStream(PropertiesUtil.class.getResource(filePath).getFile());
            prop.setProperty(parameterName, parameterValue);
            //以适合使用 load 方法加载到 Properties 表中的格式,
            //将此 Properties 表中的属性列表(键和元素对)写入输出流
            prop.store(fos, "Update '" + parameterName + "' value");
接下来说下怎么操作,先调用类名.class.getResource(filepath).getFile()即可获取到发布到服务器上的文件,然后再站华为输入输出流,这里需要注意传入的filepath
不以’/'开头时默认是从此类所在的包下取资源,以’/'开头则是从ClassPath根下获取,我要读取的文件在项目的包中就这样写"/com/sky/magnifier/config/systemplan.properties"

猜你喜欢

转载自blog.csdn.net/qq_35921773/article/details/79096149
今日推荐