Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.mkdirs() creating a directory instead of a file

Tags:

java

io

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);
    }
}
like image 585
drew moore Avatar asked Mar 04 '13 23:03

drew moore


People also ask

What is the use of mkdir () and Mkdirs () methods?

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.

How to create a new file in a new directory in Java?

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.

Does mkdir create a file?

The mkdir() method is a part of File class. The mkdir() function is used to create a new directory denoted by the abstract pathname.

What does file mkdir do?

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.


1 Answers

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();
like image 80
user207421 Avatar answered Sep 24 '22 21:09

user207421