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

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

    I would prefer to use the resourceboundle class to load the properties - just to get it done in one line instead of 5 lines code through stream, Properties class and load().

    FYI ....

        public void init(ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);
    
        try {
    
                /*** Type1 */
            Properties props = new Properties();
    
            String fileName = getServletContext().getRealPath("WEB-INF/classes/com/test/my.properties");
        //          stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
        //          stream = ClassLoader.getSystemResourceAsStream("WEB-INF/class/com/test/my.properties");  
    
            InputStream stream = getServletContext().getResourceAsStream("/WEB-INF/classes/com/test/my.properties");
    
      //        props.load(new FileInputStream(fileName));
            props.load(stream);
    
            stream.close();
            Iterator keyIterator = props.keySet().iterator();
            while(keyIterator.hasNext()) {
                    String key = (String) keyIterator.next();
                    String value = (String) props.getProperty(key);
                    System.out.println("key:" + key + " value: " + value);
            }
    
      /*** Type2:  */
      // Just get it done in one line by rb instead of 5 lines to load the properties
      // WEB-INF/classes/com/test/my.properties file            
      //            ResourceBundle rb = ResourceBundle.getBundle("com.test.my", Locale.ENGLISH, getClass().getClassLoader());
            ResourceBundle rb = ResourceBundle.getBundle("com.ibm.multitool.customerlogs.ui.nl.redirect");
            Enumeration<String> keys = rb.getKeys();
            while(keys.hasMoreElements()) {
                String key = keys.nextElement();
                System.out.println(key + " - " + rb.getObject(key));
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServletException("Error loading config.", e);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException("Error loading config.", e);
        }       
    
    }
    
    0 讨论(0)
  • 2020-11-28 09:18

    If you wanted to load message files for different languages, just use the shared.loader= of catalina.properties... for more info, visit http://theswarmintelligence.blogspot.com/2012/08/use-resource-bundle-messages-files-out.html

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