java 中直接读写properties文件

首先谈谈如何获取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();
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值