50

mybundle.txtと呼ばれるファイルがありますc:/temp-

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

14 に答える 14

69

リソース バンドル ファイルに正しい名前を付ける (拡張子 .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.coderanch.com/t/432762/java/java/absolute-path-bundle-fileのクレジット

于 2013-03-27T08:35:54.617 に答える
50

それが「有効なリソースバンドル」であると言うとき、それはプロパティリソースバンドルですか?もしそうなら、それをロードする最も簡単な方法はおそらく:

try (FileInputStream fis = new FileInputStream("c:/temp/mybundle.txt")) {
  return new PropertyResourceBundle(fis);
}
于 2009-07-23T15:13:17.113 に答える
11

の JavaDocs からResourceBundle.getBundle(String baseName):

baseName- リソース バンドルのベース名、完全修飾クラス名

これが平易な英語で意味することは、リソースバンドルがクラスパス上にある必要があり、それbaseNameはバンドルとバンドル名を含むパッケージである必要があるということmybundleです。

拡張子と、バンドル名の一部を形成するロケールを除外すると、JVM がデフォルトのロケールに従ってソートします。詳細については、 java.util.ResourceBundleのドキュメントを参照してください。

于 2009-07-23T15:14:04.320 に答える
7

JSF アプリケーションの場合

特定のファイル パスからリソース バンドル prop ファイルを取得して、JSF アプリで使用するため。

  • ResourceBundle を拡張するクラスの URLClassLoader でバンドルを設定し、ファイル パスからバンドルをロードします。
  • タグ basenameのプロパティでクラスを指定します。loadBundle<f:loadBundle basename="Message" var="msg" />

拡張 RB の基本的な実装については、 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) { }
       }
      .
      .
      .
    }

それ以外の場合は、getBundle メソッドからバンドルを取得しますが、ロケールは のような他のソースから取得しますLocale.getDefault()。この場合、新しい (RB) クラスは必要ない場合があります。

于 2012-07-31T09:46:56.307 に答える
4

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.

于 2011-07-25T16:37:48.763 に答える
2

私は、resourceboundleクラスを使用してプロパティをロードすることを好みます-ストリーム、Propertiesクラス、およびload()を介した5行のコードではなく、1行で実行するためです。

ご参考までに ....

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

}
于 2012-05-31T22:37:58.233 に答える
0

異なる言語のメッセージファイルをロードしたい場合は、catalina.propertiesのshared.loader =を使用してください...詳細については、http: //theswarmintelligence.blogspot.com/2012/08/use-resource-bundle-にアクセスしてください。 messages-files-out.html

于 2012-08-20T12:36:18.090 に答える
0

実際のファイル自体ではなく、ファイルのをクラスパスに配置したいと思います。

これを試してください(微調整が必​​要な場合があります):

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 );
于 2009-07-24T13:31:38.647 に答える
0

ファイル名には .properties 拡張子が必要で、ベース ディレクトリはクラスパスにある必要があります。それ以外の場合は、クラスパスにあるjarに入れることもできます クラスパスのディレクトリに関連して、リソースバンドルを / または で指定できます。セパレーター。「。」が好ましい。

于 2010-11-22T15:22:46.663 に答える
0

これは私のために働く:

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();
        }
    }
}           
于 2013-08-30T15:52:20.680 に答える
0
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);

    }
}
于 2014-05-30T19:58:37.097 に答える