File operations
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class FileOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\nFile Operations Menu:");
System.out.println("1. Create a File");
System.out.println("2. Update a File");
System.out.println("3. Delete a File");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (choice) {
case 1:
createFile(scanner);
break;
case 2:
updateFile(scanner);
break;
case 3:
deleteFile(scanner);
break;
case 4:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 4);
scanner.close();
}
public static void createFile(Scanner scanner) {
System.out.print("Enter the name of the file to create: ");
String fileName = scanner.nextLine();
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 updateFile(Scanner scanner) {
System.out.print("Enter the name of the file to update: ");
String fileName = scanner.nextLine();
if (!Files.exists(Paths.get(fileName))) {
System.out.println("File does not exist.");
return;
}
System.out.print("Enter the content to append to the file: ");
String content = scanner.nextLine();
try (FileWriter fileWriter = new FileWriter(fileName, true)) {
fileWriter.write(content + System.lineSeparator());
System.out.println("Successfully updated the file.");
} catch (IOException e) {
System.out.println("An error occurred while updating the file.");
e.printStackTrace();
}
}
public static void deleteFile(Scanner scanner) {
System.out.print("Enter the name of the file to delete: ");
String fileName = scanner.nextLine();
File file = new File(fileName);
while (true) {
System.out.print("Are you sure you want to delete the file? (yes/no): ");
String response = scanner.nextLine();
if (response.equalsIgnoreCase("yes")) {
if (file.delete()) {
System.out.println("File deleted successfully.");
} else {
System.out.println("Failed to delete the file.");
}
break;
} else if (response.equalsIgnoreCase("no")) {
System.out.println("File deletion canceled.");
break;
} else {
System.out.println("Invalid response. Please enter 'yes' or 'no'.");
}
}
}
}
Comments
Post a Comment