来自 JFileChooser 的文件路径为空

filePath from JFileChooser is null

我目前正在做一个项目,想将一个对象保存到一个文件 ObjectOutputStream 到用户在 JFileChooser 的帮助下选择的位置。但是对象总是保存到程序的根目录中,文件名为"null"(%ProjectDirectory%/null).

这是我的方法 saveObjects,它将 LinkedList 个对象保存到一个文件中:

public void saveObjects(String filePath) {
    try {
        FileOutputStream os = new FileOutputStream(filePath);
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeObject(oceanObjects);
        oos.close();
        os.close();
    } catch(IOException e) {
        System.err.println(e);
    }
}

此指令调用方法 saveObjectfilepath 作为参数(filePath 是一个字符串;我已经尝试使用文件)

saveObjects(view.getFilePath());

viewOceanLifeView 的实例,view.getFilePath() 是 getter 的 class 方法, returns 路径该文件应保存(作为字符串)。

getFilePath() 看起来像这样:

public String getFilePath() {
    return filePath;
}

我的 OceanLifeView 是这样的:

OceanLifeView(String title, int type) {
    if(...) {
        ...
    }else if (title.equals("fileChooser")) {
        fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(FILES_ONLY);

        if (type == 0) {
            //Load Button functions
            System.out.println("De-Serialisation started fileChooserGUI!");
            returnVal = fileChooser.showOpenDialog(fileChooser);
        } else {
            //Save Button functions
            System.out.println("Serialisation started fileChooserGUI!");
            returnVal = fileChooser.showSaveDialog(fileChooser);
        }

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            filePath = fileChooser.getSelectedFile();
        }
    }
}

如果有人能就我在实现此功能时遇到的问题或错误提供一些见解,我将非常感谢。

这看起来好像您正在将文件相对路径传递给 FileOutputStream 构造函数。

可能的原因是文件路径被计算为 filePath = selectedFile.getPath() 而不是它应该这样计算:

File selectedFile = fileChooser.getSelectedFile();
String filePath = selectedFile.getAbsolutePath();