如何在Java中从文件资源加载资源包?

发布于 2024-07-29 03:00:50 字数 653 浏览 2 评论 0 原文

我在 c:/temp 中有一个名为 mybundle.txt 的文件 -

c:/temp/mybundle.txt

如何将此文件加载到java.util.ResourceBundle? 该文件是有效的资源包。

这似乎不起作用:

java.net.URL resourceURL = null;

String path = "c:/temp/mybundle.txt";
java.io.File fl = new java.io.File(path);

try {
   resourceURL = fl.toURI().toURL();
} catch (MalformedURLException e) {             
}           

URLClassLoader urlLoader = new URLClassLoader(new java.net.URL[]{resourceURL});
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle( path , 
                java.util.Locale.getDefault(), urlLoader );

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

c:/temp/mybundle.txt

How do I load this file into a java.util.ResourceBundle? The file is a valid resource bundle.

This does not seem to work:

java.net.URL resourceURL = null;

String path = "c:/temp/mybundle.txt";
java.io.File fl = new java.io.File(path);

try {
   resourceURL = fl.toURI().toURL();
} catch (MalformedURLException e) {             
}           

URLClassLoader urlLoader = new URLClassLoader(new java.net.URL[]{resourceURL});
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle( path , 
                java.util.Locale.getDefault(), urlLoader );

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

雨轻弹 2024-08-05 03:00:50

只要正确命名资源包文件(使用 .properties 扩展名),就可以了:

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

其中“c:\temp”是保存属性文件的外部文件夹(不在类路径上),而“myResource”与myResource.properties、myResource_fr_FR.properties 等。

归功于 http://www.myResource.properties、myResource_fr_FR.properties 等。 coderanch.com/t/432762/java/java/absolute-path-bundle-file

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

深爱成瘾 2024-08-05 03:00:50

当您说它是“有效的资源包”时,它是属性资源包吗? 如果是这样,加载它的最简单方法可能是:

try (FileInputStream fis = new FileInputStream("c:/temp/mybundle.txt")) {
  return new PropertyResourceBundle(fis);
}

When you say it's "a valid resource bundle" - is it a property resource bundle? If so, the simplest way of loading it probably:

try (FileInputStream fis = new FileInputStream("c:/temp/mybundle.txt")) {
  return new PropertyResourceBundle(fis);
}
属性 2024-08-05 03:00:50

1) 更改属性的扩展名(例如 mybundle.properties。)
2) 将文件放入 jar 并将其添加到类路径中。
3)使用以下代码访问属性:

ResourceBundle rb = ResourceBundle.getBundle("mybundle");
String propertyValue = rb.getString("key");

1) Change the extension to properties (ex. mybundle.properties.)
2) Put your file into a jar and add it to your classpath.
3) Access the properties using this code:

ResourceBundle rb = ResourceBundle.getBundle("mybundle");
String propertyValue = rb.getString("key");
大海や 2024-08-05 03:00:50

来自 ResourceBundle.getBundle(String baseName) 的 JavaDocs:

baseName - 的基本名称
资源包,完全合格的
类名

用简单的英语来说,这意味着资源包必须位于类路径上,并且 baseName 应该是包含该包的包加上包名称,mybundle 在您的案件。

忽略扩展名和构成包名称一部分的任何区域设置,JVM 将根据默认区域设置为您进行排序 - 请参阅 java.util.ResourceBundle 了解更多信息。

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.

漫漫岁月 2024-08-05 03:00:50

对于 JSF 应用程序

从给定文件路径获取资源包 prop 文件以在 JSF 应用程序中使用它们。

  • 使用 URLClassLoader 为扩展的类设置包
    ResourceBundle 从文件路径加载包。
  • loadBundle 标记的 basename 属性中指定类。

有关扩展 RB 的基本实现,请参阅 示例自定义资源包

/* 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) { }
       }
      .
      .
      .
    }

否则,从 getBundle 方法获取包但区域设置来自其他来源(例如 Locale.getDefault()),在这种情况下可能不需要新的 (RB) 类。

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.

流殇 2024-08-05 03:00:50

如果像我一样,您实际上想从文件系统而不是类路径加载 .properties 文件,但保留与查找相关的所有智能,那么请执行以下操作:

  1. 创建 java.util.ResourceBundle.Control 的子类
  2. 覆盖 newBundle() 方法

在这个愚蠢的示例中,我假设您在 C:\temp 处有一个文件夹,其中包含“.properties”的平面列表 请

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;
}

注意,这支持 UTF-8,我相信默认情况下不支持 UTF-8。

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.

甜点 2024-08-05 03:00:50

这对我来说非常有效。 而且它不会每次都重新加载捆绑包。 我尝试获取一些统计信息来从外部文件位置加载和重新加载捆绑包。

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

其中“c:\temp”是保存属性文件的外部文件夹(不在类路径上),“myResource”与 myResource.properties、myResource_fr_FR.properties 等相关。

注意:如果您有如果你的类路径上有相同的包名称,那么默认情况下将使用 URLClassLoader 的构造函数来获取它。

归功于 http://www.coderanch.com/ t/432762/java/java/absolute-path-bundle-file

查找下面的一些统计信息,所有时间均以毫秒为单位。
我并不担心初始加载时间,因为这可能是我试图弄清楚的工作空间或代码的问题,但我试图展示的是重新加载的时间较少,告诉我它来自内存。

以下是一些统计数据:

  • 初始 Locale_1 加载花费了 3486
  • 重新加载 Locale_1 花费了 24
  • 重新加载 Locale_1花费了 23
  • 重新加载 Locale_1 花费了 22
  • 重新加载 Locale_1 花费了 15
  • 初始 Locale_2 加载花费了 870
  • 重新加载 Locale_2 花费了 22
  • 重新加载 Locale_2 花费了 18
  • 初始 Locale_3 加载花费了 2298
  • 重新加载 Locale_3 花费了 8
  • 重新加载Locale_3 占用了 4 个

This worked for me very well. And it doesn't reload the bundle everytime. I tried to take some stats to load and reload the bundle from external file location.

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.

Note: If you have the same bundle name on your classpath then it will be picked up by default using this constructor of URLClassLoader.

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

Find some of the stats below, all time in ms.
I am not worried about the initial load time as that could be something with my workspace or code that I am trying to figure out but what I am trying to show is the reload took way lesser telling me its coming from memory.

Here some of the stats:

  • Initial Locale_1 load took 3486
  • Reload Locale_1 took 24
  • Reload Locale_1 took 23
  • Reload Locale_1 took 22
  • Reload Locale_1 took 15
  • Initial Locale_2 load took 870
  • Reload Locale_2 took 22
  • Reload Locale_2 took 18
  • Initial Locale_3 load took 2298
  • Reload Locale_3 took 8
  • Reload Locale_3 took 4
百合的盛世恋 2024-08-05 03:00:50

我更喜欢使用 ResourceBoundle 类来加载属性 - 只是为了在一行中完成它,而不是通过流、Properties 类和 load() 的 5 行代码。

供参考 ....

    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);
    }       

}

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);
    }       

}
感性 2024-08-05 03:00:50

我认为您希望文件的父级位于类路径上,而不是实际的文件本身。

试试这个(可能需要一些调整):

String path = "c:/temp/mybundle.txt";
java.io.File fl = new java.io.File(path);

try {
   resourceURL = fl.getParentFile().toURL();
} catch (MalformedURLException e) {
   e.printStackTrace();                     
}               

URLClassLoader urlLoader = new URLClassLoader(new java.net.URL[]{resourceURL});
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("mybundle.txt", 
                java.util.Locale.getDefault(), urlLoader );

I think that you want the file's parent to be on the classpath, not the actual file itself.

Try this (may need some tweaking):

String path = "c:/temp/mybundle.txt";
java.io.File fl = new java.io.File(path);

try {
   resourceURL = fl.getParentFile().toURL();
} catch (MalformedURLException e) {
   e.printStackTrace();                     
}               

URLClassLoader urlLoader = new URLClassLoader(new java.net.URL[]{resourceURL});
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("mybundle.txt", 
                java.util.Locale.getDefault(), urlLoader );
南薇 2024-08-05 03:00:50

文件名应具有 .properties 扩展名,并且基目录应位于类路径中。 否则它也可以位于类路径中的 jar 中
相对于类路径中的目录,资源包可以用 / 或 指定。 分隔器。 “。” 是优选的。

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.

深巷少女 2024-08-05 03:00:50

如果您想加载不同语言的消息文件,只需使用
共享.loader=
catalina.properties...
有关更多信息,请访问 http://theswarmintelligence。 blogspot.com/2012/08/use-resource-bundle-messages-files-out.html

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

笨笨の傻瓜 2024-08-05 03:00:50

这对我有用:

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();
        }
    }
}           

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();
        }
    }
}           
謸气贵蔟 2024-08-05 03:00:50
public class One {

    private static One one = null;

    Map<String, String> configParameter = Collections.synchronizedMap(new HashMap<String, String>());

    private One() {
        ResourceBundle rb = ResourceBundle.getBundle("System", Locale.getDefault());

        Enumeration en = rb.getKeys();
        while (en.hasMoreElements()) {
            String key = (String) en.nextElement();
            String value = rb.getString(key);
            configParameter.put(key, value);

        }
    }

    public static One getInstance() {
        if (one == null) {
            one= new One();
        }

        return one;

    }

    public Map<String, String> getParameter() {

        return configParameter;
    }



    public static void main(String[] args) {
        String string = One.getInstance().getParameter().get("subin");
        System.out.println(string);

    }
}
public class One {

    private static One one = null;

    Map<String, String> configParameter = Collections.synchronizedMap(new HashMap<String, String>());

    private One() {
        ResourceBundle rb = ResourceBundle.getBundle("System", Locale.getDefault());

        Enumeration en = rb.getKeys();
        while (en.hasMoreElements()) {
            String key = (String) en.nextElement();
            String value = rb.getString(key);
            configParameter.put(key, value);

        }
    }

    public static One getInstance() {
        if (one == null) {
            one= new One();
        }

        return one;

    }

    public Map<String, String> getParameter() {

        return configParameter;
    }



    public static void main(String[] args) {
        String string = One.getInstance().getParameter().get("subin");
        System.out.println(string);

    }
}
没有伤那来痛 2024-08-05 03:00:50
ResourceBundle rb = ResourceBundle.getBundle("service"); //service.properties
System.out.println(rb.getString("server.dns")); //server.dns=http://....
ResourceBundle rb = ResourceBundle.getBundle("service"); //service.properties
System.out.println(rb.getString("server.dns")); //server.dns=http://....
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文