File I/O Classes: Creating Files and Directories
1. File Class:
- Represents a file or directory path.
- Provides methods for creating new files and directories.
File file = new File("newFile.txt");
try {
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
2. mkdir() Method:
- Creates a directory.
File directory = new File("newDirectory");
if (directory.mkdir()) {
System.out.println("Directory created: " + directory.getName());
} else {
System.out.println("Directory already exists.");
}
3. mkdirs() Method:
- Creates a directory and its parent directories if they do not exist.
File directories = new File("newDirectories/childDirectory");
if (directories.mkdirs()) {
System.out.println("Directories created: " + directories.getName());
} else {
System.out.println("Directories already exist.");
}
4. Path Class (Java NIO):
- Provides methods for manipulating file paths.
- Can create files and directories using Files class.
Path path = Paths.get("newFile.txt");
try {
Files.createFile(path);
System.out.println("File created: " + path.getFileName());
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
5. Files Class (Java NIO):
- Provides methods for file operations.
- Can create directories and files.
Path directoryPath = Paths.get("newDirectory");
try {
Files.createDirectory(directoryPath);
System.out.println("Directory created: " + directoryPath.getFileName());
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
These examples illustrate different ways to create files and directories in Java using various file I/O classes and methods.
Comments
Post a Comment