How to load a resource bundle from a file resource in Java?

前端 未结 14 854
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 08:19

I have a file called mybundle.txt in c:/temp -

c:/temp/mybundle.txt

How do I load this file into a java.util.Res

14条回答
  •  眼角桃花
    2020-11-28 09:01

    If, like me, you actually wanted to load .properties files from your filesystem instead of the classpath, but otherwise keep all the smarts related to lookup, then do the following:

    1. Create a subclass of java.util.ResourceBundle.Control
    2. Override the newBundle() method

    In this silly example, I assume you have a folder at C:\temp which contains a flat list of ".properties" files:

    public class MyControl extends Control {
    @Override
    public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
            throws IllegalAccessException, InstantiationException, IOException {
    
        if (!format.equals("java.properties")) {
            return null;
        }
    
        String bundleName = toBundleName(baseName, locale);
        ResourceBundle bundle = null;
    
        // A simple loading approach which ditches the package      
        // NOTE! This will require all your resource bundles to be uniquely named!
        int lastPeriod = bundleName.lastIndexOf('.');
    
        if (lastPeriod != -1) {
            bundleName = bundleName.substring(lastPeriod + 1);
        }
        InputStreamReader reader = null;
        FileInputStream fis = null;
        try {
    
            File file = new File("C:\\temp\\mybundles", bundleName);
    
            if (file.isFile()) { // Also checks for existance
                fis = new FileInputStream(file);
                reader = new InputStreamReader(fis, Charset.forName("UTF-8"));
                bundle = new PropertyResourceBundle(reader);
            }
        } finally {
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(fis);
        }
        return bundle;
    }
    

    }

    Note also that this supports UTF-8, which I believe isn't supported by default otherwise.

提交回复
热议问题