java 中直接读写properties文件
发布日期:2022-02-10 11:36:54 浏览次数:34 分类:技术文章

本文共 1733 字,大约阅读时间需要 5 分钟。

首先谈谈如何获取project中指定路径下的文件

(1)ClassLoader提供了两个方法用于从装载的类路径中取得资源:

       public URL getResource(String name); 

        public InputStream getResourceAsStream(String name);

       这里name是资源的类路径,它是相对与“/”根路径下的位置。getResource得到的是一个URL对象来定位资源,而getResourceAsStream取得该资源输入流的引用保证程序可以从正确的位置抽取数据。

        是真正使用的不是ClassLoader的这两个方法,而是Class getResourcegetResourceAsStream方法,因为 Class对象可以从你的类得到(如YourClass.class YourClass.getClass()),而ClassLoader则需要再 调用一次YourClass.getClassLoader()方法,不过根据JDK文档的说法,Class对象的这两个方法其实是“委托”delegate)给装载它的ClassLoader来做的,所以只需要使用 Class对象的这两个方法就可以了。

       因此,直接调用 this.getClass().getResourceAsStream(String name);获取流,静态化方法中则使用ClassLoader.getSystemResourceAsStream(String name); 

(2)获取当前当前ClassPath的绝对URI路径的几种写法:

this.getClass().getResource("")

this.getClass().getResource("/")

this.getClass().getClassLoader().getResource("")

ClassLoader.getSystemResource("")

Thread.currentThread().getContextClassLoader().getResource("")

其次再是文件的读写:

    public static String getStringProperty(String keyName,

            String propertyFileName) throws IOException {
        InputStream inputStream = ClassLoader
                .getSystemResourceAsStream(propertyFileName);
        Properties props = new Properties();
        props.load(inputStream);
        return props.getProperty(keyName);
    }
    public static void updateStringProperty(String keyName, String value,
            String propertyFileName) throws IOException, URISyntaxException {
        File file = new File(ClassLoader.getSystemResource(propertyFileName).toURI());
        InputStream inputStream = new FileInputStream(file);
        Properties props = new Properties();
        props.load(inputStream);    
        inputStream.close();        
        OutputStream outputStream = new FileOutputStream(file);
        props.setProperty(keyName, value);
        props.store(outputStream, "update properties:" + keyName + " to "
                + value);
        outputStream.close();
    }

转载地址:https://blog.csdn.net/courage89/article/details/9243081 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:java中DateFormat格式输出Date
下一篇:windows下配置python环境变量

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年04月16日 07时47分16秒