Write a java program for
the
following:
To create a file.
To rename a file.
To delete a file.
To display path of a file.
import java.io.File;
import java.io.IOException;
public class FileOperations {
public
static void main(String[] args) {
//
Create a file
createFile("sample.txt");
//
Rename a file
renameFile("sample.txt", "newSample.txt");
//
Display the path of a file
displayFilePath("newSample.txt");
//
Delete a file
deleteFile("newSample.txt");
}
public
static void createFile(String fileName) {
File file = new File(fileName);
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 while creating the
file.");
e.printStackTrace();
}
}
public
static void renameFile(String oldFileName, String newFileName) {
File oldFile = new File(oldFileName);
File newFile = new File(newFileName);
if
(oldFile.renameTo(newFile)) {
System.out.println("File renamed to: " + newFileName);
}
else {
System.out.println("Unable to rename the file.");
}
}
public
static void displayFilePath(String fileName) {
File file = new File(fileName);
System.out.println("File path: " + file.getAbsolutePath());
}
public
static void deleteFile(String fileName) {
File file = new File(fileName);
if
(file.delete()) {
System.out.println("File deleted: " + fileName);
}
else {
System.out.println("Unable to delete the file.");
}
}
}