【问题标题】:getting file.properties from JFileChooser and using it on ResourceBundle从 JFileChooser 获取 file.properties 并在 ResourceBundle 上使用它
【发布时间】:2017-03-23 13:49:16
【问题描述】:

目前我正在构建一个 Java 桌面应用程序,用户可以在其中通过 JFileChooser 加载 file.properties 来设置语言。但是,它向我抛出了一个异常:找不到基本名称 language.properties, locale pt_BR 的捆绑包。

我的文件名是 language.properties,所以我不知道出了什么问题。例如,我想加载默认的 language.properties 文件而不是 language_en.properties。这是我的代码:

JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
URL[] urls = null;
try {
urls= new URL[]
{
selectedFile.toURI().toURL()
};
} catch (MalformedURLException e){// TODO Auto-generated catch block
    e.printStackTrace();
}
    String fileName = selectedFile.getName();
    int pos = fileName.lastIndexOf(".");
    if (pos > 0) {
      fileName = fileName.substring(0, pos);
    }
    ClassLoader loader = new URLClassLoader(urls);
    ResourceBundle bundle = ResourceBundle.getBundle(fileName,Locale.getDefault(),loader);
}

任何帮助将不胜感激。

【问题讨论】:

  • 如果它明确表示“找不到基本名称 language.properties 的捆绑包”,那么您在此处发布的代码 sn-p 不正确:您正在调用 @ 987654322@,你应该在这里调用getBundle("language"),和sn-p一样。
  • 此外,不清楚您的选择器是否应该选择文件或文件夹。如果所选文件未命名为“language.properties”怎么办?
  • 我已经更新了我的问题。
  • 我明白了。 File.getName() 不会返回有效的包名称,正如我已经说过的:它将返回 language.properties
  • 感谢您的意见。我现在在代码上修复了它并再次更新了问题。它获取不带扩展名的文件名。但是,同样的错误。

标签: java swing file resourcebundle


【解决方案1】:

我更正了这个问题。我正在设置 urls 数组的绝对路径,但我应该只设置路径。

这是正确的代码:

    JFileChooser fileChooser = new JFileChooser();
    int returnValue = fileChooser.showOpenDialog(null);


    if (returnValue == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();

        int pos2 = selectedFile.getAbsolutePath().lastIndexOf(selectedFile.getName());
        String path = null;
        path = selectedFile.getAbsolutePath().replace(selectedFile.getName(), "");
        File file = new File(path);
        URL[] urls = null;
        try {
            urls=new URL[]{
                    file.toURI().toURL()
                    };} 
        catch (MalformedURLException e){// TODO Auto-generated catch block
                    e.printStackTrace();
                }
        String fileName = selectedFile.getName();
        int pos = fileName.lastIndexOf(".");
        if(pos > 0){
            fileName = fileName.substring(0,pos);
        }
        ClassLoader loader = new URLClassLoader(urls);
        bundle = ResourceBundle.getBundle(fileName, Locale.getDefault(), loader);
        }

我会做进一步的改进。谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多