java files

Java Create New File Folder Code With Examples

Table of Contents

Program

import java.io.File;
import java.io.IOException;
public class FileCreateMain
{
	public static void main(String[] args) 
	{
		File Obj = new File("Obj:\\program");
		if (Obj.mkdir())
		{
		    System.out.println("Directory is created");
		}
		else 
		{
		    System.out.println("Directory cannot be created");
		}
		try
		{
			File myObj = new File("filename.txt");
		if (myObj.createNewFile())
		{
			System.out.println("File created: " + myObj.getName());
		} 
		else
		{
			System.out.println("File already exists.");
		}
		} 
		catch (IOException e)
		{
			System.out.println("An error occurred.");
			e.printStackTrace();
		}
	        File f = new File("F:\\program\\program1");
  
           
        	if (f.mkdirs()) 
		{
            		System.out.println("Directory is created");
        	}
        	else 
		{
            		System.out.println("Directory cannot be created");
	        }
	}
}

Output

Directory cannot be created
File already exists.
Directory cannot be created

Description

public boolean mkdir()

Creates the directory named by this abstract pathname.

Returns:

true if and only if the directory was created; false otherwise

Throws:

SecurityException – If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method does not permit the named directory to be created

public boolean mkdirs()

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

Returns:

true if and only if the directory was created, along with all necessary parent directories; false otherwise

Throws:

SecurityException – If a security manager exists and its SecurityManager.checkRead(java.lang.String) method does not permit verification of the existence of the named directory and all necessary parent directories; or if the SecurityManager.checkWrite(java.lang.String) method does not permit the named directory and all necessary parent directories to be created