tags:

views:

237

answers:

1

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?

+6  A: 

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;
}
bruno conde
thank you, confusing that java does not seem to differentiate files from folders
Gerard
How should Java do that? What is “a”, a file or a directory? Why should “foo.dat” be a file and not a directory? You have to tell Java what you want. If you tell Java to create a directory named “index.html”, it will happily create a directory with the name of “index.html”. :)
Bombe
your remark comes from a programmers perspective, my confusion was from a user perspective, because a computer-user differentiates between folders and files; java could have chosen to support human beings e.g. with a filetype enum
Gerard
Many file systems do not differentiate between files and folders. (folders are files) Java is merely mirroring this design.
windfinder
Well, when Java doesn't differentiate, I must be purely lucky that the above solution works. Will it work on linux OS as well, and how do you know, apart from an experimental test?
Gerard
@Gerard: The Java type "File" is just an abstraction of a filesystem object. The above code will work equally well on any JVM and on any OS. Whether you choose to treat the given File object as a file or directory is up to you. If you're just querying the filesystem and need to know whether an existing filesystem object is a file or directory, you should call one of the boolean methods File.isDir() or File.isFile(). I always try to use one of these more specific methods instead of File.exists().
rob
@Gerard: Also note that the File.createNewFile() method is not explicitly necessary in your example. FileOutputStream will create the new file if you don't do it yourself.
rob
@rob: I still cannot see how the java abstraction of "File" is logically consistent in this example. On Windows and Linux, after file.getParentFile().mkdirs(); file.createNewFile(); the jvm definitely made a file, not a folder. So it is not "up to me" and the result is not 100% logically consistent with the documentation.
Gerard