Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a file in java (not a folder) ?

Tags:

java

Perhaps somewhat embarassing, but after some hours I still cannot create a file in Java...

File file = new File(dirName + "/" + fileName);
try
{
    // --> ** this statement gives an exception 'the system cannot find the path'
    file.createNewFile();
    // --> ** this creates a folder also named a directory with the name fileName
    file.mkdirs();
    System.out.println("file != null");
    return file;
}
catch (Exception e)
{
    System.out.println(e.getMessage());
    return null;
}

What am I missing here?

like image 836
Gerard Avatar asked Aug 04 '09 13:08

Gerard


People also ask

How do you create a new file in Java?

java File file = new File("JavaFile. java"); We then use the createNewFile() method of the File class to create new file to the specified path.

How do you create a file in Java if it does not exist?

Java creating file with File The File's createNewFile method creates a new, empty file named by the pathname if a file with this name does not yet exist. The createNewFile returns true if the named file does not exist and was successfully created; false if the named file already exists.

How do you create a file and 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.


1 Answers

Try creating the parent dirs first:

File file = new File(dirName + File.separator + fileName);
try {
    file.getParentFile().mkdirs();
    file.createNewFile();
    System.out.println("file != null");
    return file;
}
catch (Exception e)
{
    System.out.println(e.getMessage());
    return null;
}
like image 88
bruno conde Avatar answered Oct 13 '22 00:10

bruno conde