私は現在プロジェクトで作業しており、ユーザがJFileChooser
の助けを借りて選択した場所にObjectOutputStream
というファイルにオブジェクトを保存したいとします。しかし、オブジェクトは常にプログラムのルートディレクトリに "null"というファイル(%ProjectDirectory%/null
)に保存されます。ここでfilePath from JFileChooserはnullです
は、ファイルにオブジェクトのLinkedList
を節約する私の方法saveObjects
、です:
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);
}
}
この命令は、filePath
はStringです(パラメータとしてfilepath
と方法saveObject
を呼び出し、私はすでに使用してみましたファイル)
saveObjects(view.getFilePath());
view
はOceanLifeView
とview.getFilePath()
のインスタンスでは、そのクラスのゲッターメソッドでありますファイルを(Stringとして)保存するパスを返します。
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();
}
}
}
私が遭遇した問題や間違いのためのいくつかの洞察を共有することができます誰にも非常に感謝するでしょう私はこの機能を実装しました。
Does'view.getFilePath() 'あなたが最後に割り当てられた同じ' filePath'文字列を返します。その
考えられる原因は、filePathには
filePath = selectedFile.getPath()
のように計算される代わりに、それはこのように計算されなければならないということですか? – MNos@MNos:OceanLifeViewクラスのOceanLifeViewコンストラクタの外側でfilePathを初期化して、getterメソッドでアクセスしました。 – Jub
'saveObjects'メソッドの最初の行に' System.out.println( "filePath:" + filePath);を追加して、出力を提供できますか? – MNos