JAVA读取propertise文件内容两种方式

本文介绍了在Java中使用不同方法读取配置文件的具体实现,包括通过反射获取资源、使用ResourceBundle以及直接通过文件流读取的方式,并展示了如何处理文件路径问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    /**
     * 读取propertise文件
     * @throws IOException
     */
    @Test
    public void fun1() throws IOException {
        /*方式一【采用反射的方式获取】:最常用的方式。常用于读取同一文件夹下的文件,若不在同一文件夹下,需要往上层找*/
        InputStream inputStream = this.getClass().getResourceAsStream("../../../../config.properties");//相对路径
        InputStream inputStream = this.getClaa().getClassLoader().getResourceAsStream("华融湘江的ID.txt");//获取类加载路径,读取src下的文件
        Properties properties = new Properties();
        properties.load(inputStream);
        System.out.println(properties.getProperty("password"));;

        /*方式二【采用ResourceBundle来获取本地资源】:只适用于资源文件在src下面的情况*/
        ResourceBundle resourceBundle = ResourceBundle.getBundle("config");
        System.out.println(resourceBundle.getString("DMUserName"));


        /*方式三:以文件流的形式读取*/
        Properties properties = new Properties();
        properties.load(new FileReader("config.properties"));   
        System.out.println(properties.getProperty("password"));
        System.out.println(URLDecoder.decode(this.getClass().getResource("").getPath(),"utf-8"));//获取当前类所在的项目路径
    }

项目结构如下:

public class ReadText {

    public static void main(String[] args) {
        try {
            //FileReader fileReader = new FileReader("E:/银监会/华融湘江的ID.txt");
            InputStream in = ReadText.class.getClassLoader().getResourceAsStream("华融湘江的ID.txt");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            StringBuilder builder = new StringBuilder("0");
            String str = "";
            while((str=bufferedReader.readLine()) != null) {
                builder.append(","+str);
            }
            System.out.println(builder);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值