Many beginners confused with the fact that same class
java.io.File is used to
create both file and directory in Java. I agree, this is not very intuitive and junior developers probably start looking for a class called
java.io.Directory, which doesn't exists. On the other hand, creating file and directory are simple in Java, as
java.io.File provides methods like
createNewFile() and
mkdir() to create new file and directory in Java. These method returns boolean, which is result of that operation i.e.
createNewFile() returns true if it successfully created file and
mkdir() returns true if directory is created successfully. There is another method called
mkdirs(), which you can use if parent directory doesn't exists, it's like
mkdir -p option from UNIX mkdir command. In this Java program, we will learn
how to create file and directory, only if they don't exists already. For checking, whether a file or directory exists or not, we will use
java.io.File.exists() method, this method returns true, if file or directory is already there. To see complete behaviour in action, please run this program twice with same inputs. First time it will create directory and file, and second time, it will just say that they already exists.