2016-07-03 19 views
0

我目前正在開發一個項目,並希望將一個對象保存到ObjectOutputStream的文件中,並將其保存到用戶在JFileChooser幫助下選擇的位置。但該對象始終保存到程序的根目錄中,並保存到名爲「null」(%ProjectDirectory%/null)的文件中。JFileChooser的filePath爲空

這裏是我的方法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); 
    } 
} 

該指令要求與filepath作爲參數(filePath方法saveObject是一個字符串,我已經嘗試過使用文件)

saveObjects(view.getFilePath()); 

viewOceanLifeViewview.getFilePath()一個實例是類的一個吸氣劑方法,該方法返回文件應保存的路徑(作爲字符串)。

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

我會非常感謝任何人誰可以分享一些見解,因爲我遇到的問題或錯誤我實現了這個功能。

+0

Does'view.getFilePath()'返回相同的'filePath'字符串在結尾分配的? – MNos

+0

@MNos:是的,我在OceanLifeView類的OceanLifeView構造函數外部初始化filePath,以使用getter方法訪問它。 – Jub

+0

您可以在'saveObjects'方法的第一行添加'System.out.println(「filePath:」+ filePath);'併爲我們提供輸出嗎? – MNos

回答

0

這看起來好像您正在將文件相對路徑傳遞給FileOutputStream構造函數。

的是可能的原因是文件路徑爲filePath = selectedFile.getPath(),而不是它應該這樣計算計算:

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

這樣做會引發此錯誤:線程「AWT-EventQueue-0」中的異常java.lang.NullPointerException – Jub

+0

您可以發送堆棧跟蹤的一部分 - 從此上下文我不明白在哪裏出現異常發生了。我的猜測是fileChooser在代碼運行時沒有初始化 - 但沒有例外的堆棧跟蹤,這只是猜測。 – river

+0

好吧......因爲它會接收'String filePath = selectedFile.getAbsolutePath();'不會將文件路徑保存到'filePath'中。所以'view.getFilePath()'返回'null' – Jub