Saturday, December 3, 2011

How to Create File and Directory in Java Example - Java IO Tutorial

How to create File and directory in Java is probably the first things come in mind when we exposed to file system from Java. Java provides rich IO API to access contents of File and Directory in Java and also provides lots of utility method to create file, delete file, read from file, and write to file or directory. Anybody who wants to develop application in Java should have a solid understanding of IO and Networking package. In this Java File Tutorial we will basics of File and Directory in Java, How to Create File and Directory in Java, Utility methods provided by File API and Common Exception or Error you will face during File and Directory Creation or access time. Creating File is different than creating Thread in java as you don’t have to implement any interface for making a Class as File in Java.


File in Java is also getting its place on various core java interviews questions specially after introduction of java.nio package and concepts like In Memory Files, we will discuss about those in probably another blog post but what it confirms is importance of knowledge of File IO for java programmer.

How to Create File and Directory in Java Example

What is File in Java

create file and directory in java example tutorialLet’s start with first basic questions “What is File in Java”, File is nothing but a simple storage of data, in java language we call it one object belongs to Java.io package it is used to store name of the file or directory and also the pathname. Instance of this class represents the name of a file or directory on the file system. Also this object can be used to create, rename, or delete the file or directory it represents. Important point to remember is that java.io.File object can represent both File and Directory in Java.  You can check whether a File object is a file in filesystem by using utility method isFile() and whether its directory in file system by using isDirectory(). Since File permissions is honored while accessing File form Java, you can not write into a read only files, there are utility methods like canRead() and CanWrite().

PATH Separator for File in Java

Path Separator for file in Java depends on which operating system you are working , in Microsoft Windows platform its “\”  while in Unix and Linux platform its forward slash “/”. You can access file system separator in Java by system property file.separator and its also made available from File Class by public static field separator.

Constructors for creating File in Java


·          File(String PathName) :it will create file object within the current directory

·          File(String dirName,string fname):it will create file object inside  a directory which is passed as first argument  and second argument is child of that directory which can be a file or a directory

·          File(File dir,String name):create new file object inside the dir as a parent of the second argument which can be a file name or a directory name.

Java File Class Method Summary

Before you start creating files and directory in Java its good to get familiar with what kind of operations are exposed via File Class API.l Here I have described only some important method which is commonly used while dealing with File and Directory in Java

·          Public string getName(): returns the name of file.

·          Public boolean exists():returns true if file exist or return false

·          Public boolean createNewFile():this method create new empty file if file not exist.return false if file not created and already exist..

·          Public boolean delete():delete the file and return true.

·          Public boolean mkdirs(): return true if directory created successfully or false

·          Public string getPath() :return the path or location of file object

·          CanRead() and CanWrite() for checking whether File or Directory is read only or not.

·          setReadOnly(), listFiles() for making file as read only in Java and listing files from directory in Java.

I suggest going through Java documentation for full list of methods and having a look most of the methods of File Class in Java is self explanatory.

Common Exception occurs during File Handling:

Some common exception related with the method of File object and their operation which we need to take care when deal with files. You can get these exceptions while opening File in Java, While Creating Files in Java or during reading and writing from File or Directory in Java. Whole File System is protected by SecurityManager in Java and Applets or other Java program from untrusted source is not allowed to access File System from Java to protect User from any Internet threat.

·          IOException:if anyI/O error occurred we got this Exception
·          SecurityException: this exception we get when security Manger exist its checkWrite or checkRead method denies to access the file
·          IllegalArgumentException:if method argument we are passing is invalid then we get this exception
·          MalFormedUrlException:this kind of exception is generated if path cannot be parsed a URL

Example of How to Create File in Java

Here is a simple example of how to create file in Java:

import java.io.*;

public class FileExample {

public static void main(String[] args) {
boolean flag = false;

// create File object
File stockFile = new File("d://Stock/stockFile.txt");

try {
    flag = stockFile.createNewFile();
} catch (IOException ioe) {
     System.out.println("Error while Creating File in Java" + ioe);
}

System.out.println("stock file" + stockFile.getPath() + " created ");

}
}

In this example of creating File in Java we have created one new file called stock file inside the stock directory on d drive first time when we execute this program it will check for the file if it will not get that file simply create the new file and flag will become true, next time when we again run this program the file is already get created inside d:\\stock folder so it will not create the file and flag value will be false.

Example of How to Create Directory in Java

Just like above example of creating file in Java we can create directory in Java, only difference is that we need to use mkdir() method to create directory in Java

import java.io.*;

public class DirectoryExample {

public static void main(String[] args) {
boolean dirFlag = false;

// create File object
File stockDir = new File("d://Stock/ stockDir ");

try {
   dirFlag = stockDir.mkdir();
} catch (SecurityException Se) {
System.out.println("Error while creating directory in Java:" + Se);
}

if (dirFlag)
   System.out.println("Directory created successfully");
else
   System.out.println("Directory was not created successfully");
}
}


That’s all on how to create File and Directory in Java , as I suggest Java IO package is an important package both for beginners in Java and with others and giving time to understand methods and operations of file Class in Java and overall IO package in Java is worth effort.

Other Related Java Tutorial

7 comments :

farhan khwaja said...

A nice post.. Never thought this can also be done.. here is my link on how to read and write into files in java Reading and Writing to Files a Java Tutorial

Javin @ tar command in unix said...

Thanks for you comment keval . Good to know that you like my file creation tutorial. What is worth to remember is that closing any file which has been opened by java Program and handling of File related exception to make your Java program more robust. You may also like my new tutorial on files as How to read and write from text File in Java

Anonymous said...

These are very nice examples.
Very clear and easy to understand every one.

Anonymous said...

Nice explanation. I wish you did not use the hard-coded path in your example but use path separator to create a file instead. It somewhat defeats the purpose of your own tutorial.

Javin @ spring interview questions answers said...

Hi Anonymous, thanks for your comment. Indeed using PATH separator is great idea that makes your code to run on both windows and unix, but samples are just to do it quick rather than do it perfectly but yes in production code path should not be hardcoded.

Vimala Yadav said...

Hi, I am Vimala i need a complete program like:
There is a file or folder in that 100 resumes are there, we have to find a perticuler name and phone no among those resumes and print that name and phone no using simple core java program.
(There is a file or folder in that 100 resumes we have to search a name and phone no and print using simple core java program)
Please help me out please
My mail id: vimalayadavn@gmail.com
please please send a compleat program to my mail id please.............

Anonymous said...

Can anyone show me how do I create a file with a name come from a user input?

Post a Comment