读取src下的属性文件的某个key值

Java 读取src下某个字段(KEY)的值(VALUE),下边几种方法,可以试试。

myProperty.properties文件位于src下,其内容为:file.upload.folder        =e:/myupload

 

package com.zxr.read.propertiesfile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;

public class ReadOneValue {

    /**
     * 读取src下某个属性文件中的某个key所对应的value
     *
     * @param args
     *
     */

    public static void main(String[] args) {

        String key = "file.upload.folder";
        String propertiesFileFullName = "myProperty.properties";
        String pbundle = "myProperty";

        fun1(propertiesFileFullName, key);
        fun2(propertiesFileFullName, key);
        fun3(pbundle, key);
    }

    // 方法一
    public static void fun1(String propertiesFileFullName, String key) {
        Properties pop = new Properties();
        InputStream fs = null;
        try {
            fs = ReadOneValue.class.getClassLoader().getResourceAsStream(
                    propertiesFileFullName);
            pop.load(fs);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String value = pop.getProperty(key);
        System.out.println("属性文件的上传路径为:" + value);
    }

    // 方法二
    public static void fun2(String propertiesFileFullName, String key) {
        Properties pop = new Properties();
        String classpath = Thread.currentThread().getContextClassLoader()
                .getResource("").getPath();

        FileInputStream fs = null;
        try {
            fs = new FileInputStream(classpath + "/" + propertiesFileFullName);
            pop.load(fs);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String value = pop.getProperty(key);
        System.out.println("读取到的值为:" + value);
    }

    // 方法三
    public static void fun3(String filename, String key) {
        Locale locale = Locale.getDefault();
        ResourceBundle localResource = ResourceBundle.getBundle(filename,
                locale);
        String value = localResource.getString(key);
        System.out.println("读取到的值为:" + value);
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值