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?
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.
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.
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.
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;
}
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