java.util.MissingResourceException: Can‘t find bundle for base name db, locale zh_CN问题解决

使用 java.util.ResourceBundle 来读取配置文件(.properties)文件得到时候报错:
java.util.MissingResourceException: Can't find bundle for base name db, locale zh_CN
代码:
ReflectTest07.java (读取.properties配置文件):

import java.util.ResourceBundle;
/**
 * 资源绑定器
 */
public class ReflectTest07 {
    
    
    public static void main(String[] args) {
    
    
        //注意: ResourceBundle.getBundle("xxxx") 不需要写扩展名
        ResourceBundle bundle = ResourceBundle.getBundle("studentInfo");
        String pathname = bundle.getString("pathname");
        System.out.println(pathname);
        
        bundle = ResourceBundle.getBundle("db");
        String username = bundle.getString("username");
        System.out.println(username);
    }
}

db.properties:

username=root

studentInfo.properties:

pathname=Student

当前三个文件的存放位置如下图:
在这里插入图片描述
运行后结果如下:
在这里插入图片描述
只能读取到studentInfo.properties中的配置信息,后面报错。

资源绑定器:java.util包下的,用于获取xxx.properties文件下的内容
经了解,使用这种方式只能绑定扩展名为.properties文件,并且这个文件必须在src路径下(即默认搜索路径是src下),如果文件不是直接在src下,而是在其子目录中,则需要写出访问的相对路径。

上面studentInfo.properties是直接在src目录下,所以可以通过ResourceBundle.getBundle(“studentInfo”);访问到该文件中的信息;
而db.properties是不是直接在src目录下,需要通过写出相对路径才能访问到,即ResourceBundle.getBundle(“database/db”);

修改后ReflectTest07.java (读取.properties配置文件):

import java.util.ResourceBundle;

/**
 * 资源绑定器
 */
public class ReflectTest07 {
    
    
    public static void main(String[] args) {
    
    
        //注意: ResourceBundle.getBundle("xxxx") 不需要写扩展名
        ResourceBundle bundle = ResourceBundle.getBundle("studentInfo");
        String pathname = bundle.getString("pathname");
        System.out.println(pathname);
        
        bundle = ResourceBundle.getBundle("database/db");
        String username = bundle.getString("username");
        System.out.println(username);
    }
}

运行结果:
在这里插入图片描述
问题解决!

猜你喜欢

转载自blog.csdn.net/weixin_45041745/article/details/120053816
今日推荐