Java Create Single Directory and Multiple Directories
To create a new directory in java, following package is getting used
1) import java.io.File - To handle file operations
2) import java.io.IOException - To handle any exceptions occur during the directory operation
While creating a directory, following things need to be checked:
1) The directory to be created, exists or not. It can be checked using the exists() method
2) If the above condition return false, the method mkdir() is called in order to create single directory.
3) If the above condition return false, the method mkdirs() is called in order to create multiple directories.
As mentioned in the code, if exists() method return false we go ahead with the file creation
At first execution the output will be "Single Directory is created!", Multiple Directories created!
After first execution, output will be "Directory already exists", Directories already exists
To create a new directory in java, following package is getting used
1) import java.io.File - To handle file operations
2) import java.io.IOException - To handle any exceptions occur during the directory operation
While creating a directory, following things need to be checked:
1) The directory to be created, exists or not. It can be checked using the exists() method
2) If the above condition return false, the method mkdir() is called in order to create single directory.
3) If the above condition return false, the method mkdirs() is called in order to create multiple directories.
package com.file;
import java.io.File;
import java.io.IOException;
public class DirectoryCreate {
public static void main(String[] args) throws IOException {
File directory = new File("D:\\kumar\\Blogs\\File Operations\\Directory");
if (directory.exists()) {
System.out.println("Directory already exists");
} else {
directory.mkdir();
System.out.println("Single Directory is created!");
}
File directories = new File("D:\\kumar\\Blogs\\File Operations\\Directory\\Directory1\\Directory4");
if (directories.exists()) {
System.out.println("Directories already exists");
} else {
directories.mkdirs();
System.out.println("Multiple Directories created!");
}
}
}
As mentioned in the code, if exists() method return false we go ahead with the file creation
At first execution the output will be "Single Directory is created!", Multiple Directories created!
After first execution, output will be "Directory already exists", Directories already exists
No comments:
Post a Comment