16

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?

2 Answers 2

25

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; } 
Sign up to request clarification or add additional context in comments.

8 Comments

thank you, confusing that java does not seem to differentiate files from folders
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”. :)
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
Many file systems do not differentiate between files and folders. (folders are files) Java is merely mirroring this design.
@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().
|
1
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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.