Jub Jub - 5 months ago 17
Java Question

filePath from JFileChooser is null

I am currently working on a Project and would like to save an object to a file with

ObjectOutputStream
to a location the user chooses with the help of a
JFileChooser
. But the object is always saved to the root directory of the program into the file named "null" (
%ProjectDirectory%/null
).

Here's my method
saveObjects
, which saves a
LinkedList
of objects to a file:

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


This instruction calls the method
saveObject
with the
filepath
as a parameter (
filePath
is a String; I already tried to use a File)

saveObjects(view.getFilePath());


view
is an instance of
OceanLifeView
and
view.getFilePath()
is a getter-method of that class that returns the path where the file should be saved (as a String).

getFilePath() looks like this:

public String getFilePath() {
return filePath;
}


And my OceanLifeView like this:

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


I would be very thankful to anybody who can share some insight for the problem I encounter or mistake I made implementing this functionality.

Answer

This looks as if you are passing files relative path to FileOutputStream constructor.

Probable cause of that is that filePath is calculated as filePath = selectedFile.getPath() instead it should be calculated like this:

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