Wednesday, August 11, 2021

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

How to create a File and directory in Java is probably the first thing that come to mind when we are exposed to the file system from Java. Java provides rich IO API to access contents of File and Directory in Java and also provides lots of utility methods to create a file, delete a file, read from a file, and write to file or directory. Anybody who wants to develop an 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 Files and Directories in Java, the Utility methods provided by File API, and Common Exception or Errors you will face during File and Directory Creation or access time. 

By the way, creating a File is different than creating Thread in java as you don’t have to implement any interface for making a Class as a File in Java.

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


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 the first basic question “What is File in Java”, File is nothing but simple storage of data, in java language we call it one object belongs to Java.io package it is used to store the name of the file or directory and also the pathname. An 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. 

An 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 from 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 name):it will create file object inside  a directory which is passed as the first argument  and the 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 a 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 the file as read only in Java and listing files from a directory in Java.

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




Common Exception occurs during File Handling:


Some common exceptions related to the method of File objects and their operation which we need to take care of when to 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

The whole File System is protected by SecurityManager in Java and Applets or other Java program from untrusted sources is not allowed to access the File System from Java to protect the User from any Internet threat.

·          IOException: if anyI/O error occurred we got this Exception
·          SecurityException: this exception we get when security Manager 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 the path cannot be parsed a URL

Example of How to Create File in Java

Here is a simple example of how to create a 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 a 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 the above example of creating a file in Java we can create a directory in Java, the only difference is that we need to use mkdir() method to create a 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

11 comments :

Farhan 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.

Unknown 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?

Unknown said...

Hi , i need program for below statement , Please help me
please send it my email
email : sowjir.netdev@gmail.com
Design & code a very simple in-memory file system and expose the file system operations e.g. create, read, write, list over HTTP.
code should:

* Be modular and re-usable

* Be Easy to test

* Demonstrate Object oriented features of the language (for Java)

* Demonstrate the use of the right data structures

* Demonstrate the use of the right design pattern

Unknown said...

Really nice and different Technic. Easy to understand each function.
thanks.

Unknown said...

How to write program in java create folder and store multiple files then count how many files are stored in folder

Unknown said...

import java. io.DataInputStream;
import java. io. File;
import java. io. Exception ;
Class file
{
public static void main(String args[])
{
DataInputStream in=new DataInputStream(System. in);
String r="" ;
Try
{
r=in. readLine() ;
String s1 =r +".txt";
File f1=new File(s1) ;
f1. createNewFile() ;
} catch(Exception e) {}
}
}

Post a Comment