I am trying to serialize the following class:
public class Library extends ArrayList<Book> implements Serializable{
public Library(){
check();
}
using the following method of that class:
void save() throws IOException {
String path = System.getProperty("user.home");
File f = new File(path + "\\Documents\\CardCat\\library.ser");
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream (f));
oos.writeObject(this);
oos.close();
}
However, rather than creating a file called library.ser
, the program is creating a directory named library.ser
with nothing in it. Why is this?
If its helpful, the save() method is initially called from this method (of the same class):
void checkFile() {
String path = System.getProperty("user.home");
File f = new File(path + "\\Documents\\CardCat\\library.ser");
try {
if (f.exists()){
load(f);
}
else if (!f.exists()){
f.mkdirs();
save();
}
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(Library.class.getName()).log(Level.SEVERE, null, ex);
}
}
The mkdirs() method is a part of File class. The mkdirs() function is used to create a new directory denoted by the abstract pathname and also all the non existent parent directories of the abstract pathname. If the mkdirs() function fails to create some directory it might have created some of its parent directories.
File provides methods like createNewFile() and mkdir() to create new file and directory in Java. These methods returns boolean, which is the result of that operation i.e. createNewFile() returns true if it successfully created file and mkdir() returns true if the directory is created successfully.
The mkdir() method is a part of File class. The mkdir() function is used to create a new directory denoted by the abstract pathname.
The mkdir() function creates a new, empty directory whose name is defined by path. The file permission bits in mode are modified by the file creation mask of the job and then used to set the file permission bits of the directory being created.
File.mkdirs() creating a directory instead of a file
That's what it's supposed to do. Read the Javadoc. Nothing there about creating a file.
f.mkdirs();
It is this line that creates the directory. It should be
f.getParentFile().mkdirs();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With