How to create File and Directory in Java Example

Create a File 

Whenever the data is need to be stored, a file is used to store the data. File is a collection of stored information that are arranged in string, rows, columns and lines etc.
In this section, we will see how to create a file. This example takes the file name and text data for storing to the file.
For creating a new file File.createNewFile( ) method is used. This method returns a boolean value true if the file is created otherwise return false. If the mentioned file for the specified directory is already exist then the createNewFile() method returns the false otherwise the method creates the mentioned file and return true. 
Lets see an example that checks the existence of  a specified file.

public class CreateFile1{
  public static void main(String[] args) throws IOException{
  File f;
  f=new File("myfile.txt");
  System.out.println("New file \"myfile.txt\" has been created
  to the current directory");
First, this program checks, the specified file "myfile.txt" is exist or not. if it does not exist then a new file is created with same name to the current location.
Create Directory

This program  explains the process of creating all non-existent ancestor directories automatically. We will use the class File class to crate the directory.

Class File
The File class an abstract representation of file and directory pathnames. File class is used to interact with the files system.

Here is the code for creating directory and all non-existing ancestor directories:
class CreateDirectory
public static void main(String args[])
String strDirectoy ="test";
String strManyDirectories="dir1/dir2/dir3";

//Create one directory
boolean success = (
 new File(strDirectoy)).mkdir();
//Create multiple directories
success =(newFile(strManyDirectories)).mkdirs();

}catch(Exception e){//Catch exception if any

People who read this post also read :


Post a Comment


Twitter Delicious Facebook Digg Stumbleupon Favorites More