Reputation: 13417
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?
Upvotes: 16
Views: 11033
Reputation: 8761
String dirName="c:\\dir1\\dir2";
String fileName="fileName.txt";
File file = new File(dirName + "/" + fileName);
try {
new File(dirName).mkdirs(); // directory created here
file.createNewFile(); // file created here
System.out.println("file != null");
return file;
}catch(Exception e)
{
System.out.println(e.getMessage());
return null;
}
Upvotes: 1
Reputation: 48255
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;
}
Upvotes: 25