从 JFileChooser 获取 file.properties 并在 ResourceBundle 上使用它



目前我正在构建一个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);
}

任何帮助将不胜感激。

我纠正了这个问题。我正在设置 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);
        }

我将进一步改进。谢谢。

最新更新