Thursday, February 13, 2020

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

Oracle Java Tutorial and Materials, Oracle Java Guides, Oracle Tutorial and Material, Oracle Java Prep

How to create File and directory in Java is probably the first things come to mind when we 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 method 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 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 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 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 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


Oracle Java Tutorial and Materials, Oracle Java Guides, Oracle Tutorial and Material, Oracle Java Prep
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.

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

Related Posts

0 comments:

Post a Comment