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

前端 未结 14 798
没有蜡笔的小新
没有蜡笔的小新 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 08:54

    As long as you name your resource bundle files correctly (with a .properties extension), then this works:

    File file = new File("C:\\temp");
    URL[] urls = {file.toURI().toURL()};
    ClassLoader loader = new URLClassLoader(urls);
    ResourceBundle rb = ResourceBundle.getBundle("myResource", Locale.getDefault(), loader);
    

    where "c:\temp" is the external folder (NOT on the classpath) holding the property files, and "myResource" relates to myResource.properties, myResource_fr_FR.properties, etc.

    Credit to http://www.coderanch.com/t/432762/java/java/absolute-path-bundle-file

    0 讨论(0)
  • 2020-11-28 08:56

    From the JavaDocs for ResourceBundle.getBundle(String baseName):

    baseName - the base name of the resource bundle, a fully qualified class name

    What this means in plain English is that the resource bundle must be on the classpath and that baseName should be the package containing the bundle plus the bundle name, mybundle in your case.

    Leave off the extension and any locale that forms part of the bundle name, the JVM will sort that for you according to default locale - see the docs on java.util.ResourceBundle for more info.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 09:05

    The file name should have .properties extension and the base directory should be in classpath. Otherwise it can also be in a jar which is in classpath Relative to the directory in classpath the resource bundle can be specified with / or . separator. "." is preferred.

    0 讨论(0)
  • 2020-11-28 09:05

    This works for me:

    File f = new File("some.properties");
    Properties props = new Properties();
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(f);
        props.load(fis);
    } catch (FileNotFoundException e) {
        e.printStackTrace();                    
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fis != null) {
            try {
                fis.close();
                fis = null;
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
    }           
    
    0 讨论(0)
  • 2020-11-28 09:08

    For JSF Application

    To get resource bundle prop files from a given file path to use them in a JSF app.

    • Set the bundle with URLClassLoader for a class that extends ResourceBundle to load the bundle from the file path.
    • Specify the class at basename property of loadBundle tag. <f:loadBundle basename="Message" var="msg" />

    For basic implementation of extended RB please see the sample at Sample Customized Resource Bundle

    /* Create this class to make it base class for Loading Bundle for JSF apps */
    public class Message extends ResourceBundle {
            public Messages (){
                    File file = new File("D:\\properties\\i18n");  
                    ClassLoader loader=null;
                       try {
                           URL[] urls = {file.toURI().toURL()};  
                           loader = new URLClassLoader(urls); 
                           ResourceBundle bundle = getBundle("message", FacesContext.getCurrentInstance().getViewRoot().getLocale(), loader);
                           setParent(bundle);
                           } catch (MalformedURLException ex) { }
           }
          .
          .
          .
        }
    

    Otherwise, get the bundle from getBundle method but locale from others source like Locale.getDefault(), the new (RB)class may not require in this case.

    0 讨论(0)
提交回复
热议问题