Menu
Topics Index
...
`

FileDemo - Java Example Program


FileDemo
import java.io.*;

class CreatingFilesandFolders
{
    public static void main(String[] args) throws IOException
    {
        File folder = new File("E:JavaPrograms\\FolderOne\\"); // LINE A
    
        if(folder.mkdirs()) // LINE B
            System.out.println("Folder created.");
        else if(folder.exists()) // LINE C
            System.out.println("Folder already exists.");
        System.out.println(folder.getPath()); // LINE D
    
        File fileOne = new File(folder, "fileOne.txt"); // LINE E
        File fileTwo = new File(folder, "fileTwo.txt"); // LINE F
        
        if(fileOne.createNewFile() && fileTwo.createNewFile()) // LINE G
            System.out.println("Files created.");
        
        else if(fileOne.exists() && fileTwo.exists())
            System.out.println("files already exists");
        System.out.println(fileOne.getPath() + "\n" + fileTwo.getPath()); // LINE H
                                                                            
    }

}
OUTPUT

Folder created.
E:JavaPrograms\FolderOne
Files created.
E:JavaPrograms\FolderOne\fileOne.txt
E:JavaPrograms\FolderOne\fileTwo.txt

DESCRIPTION

At LINE A we are creating an absolute path string for folder.
At LINE B we are creating folder here mkdirs create folders and returns true if the folders are created otherwise false.
At LINE C we are checking whether the folder already exists.
At LINE D we are printing the path of folder.
At LINE E and LINE F we are creating absolute path for files.
At LINE G we are creating files using createNewFile.
At LINE H we are printing the file paths.

THINGS TO TRY
  • Create one more folder FolderTwo in JavaPrograms folder.
  • Create two more files fileThree and fileFour in FolderTwo.

© meritcampus 2019

All Rights Reserved.

Open In App