File operation program
import java.io.*;
import java.util.Scanner;
public class FileOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String fileName = "example.txt";
int choice;
do {
System.out.println("Choose an action: ");
System.out.println("1. Read");
System.out.println("2. Write");
System.out.println("3. Update");
System.out.println("4. Delete");
System.out.println("5. Exit");
choice = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (choice) {
case 1:
readFile(fileName);
break;
case 2:
System.out.print("Enter text to write: ");
String textToWrite = scanner.nextLine();
writeFile(fileName, textToWrite);
break;
case 3:
System.out.print("Enter new text: ");
String newText = scanner.nextLine();
updateFile(fileName, newText);
break;
case 4:
deleteFile(fileName);
break;
case 5:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 5);
scanner.close();
}
private static void readFile(String fileName) {
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
}
}
private static void writeFile(String fileName, String text) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
bw.write(text);
System.out.println("Text written to file successfully.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
}
}
private static void updateFile(String fileName, String newText) {
try {
FileWriter fw = new FileWriter(fileName, false);
fw.write(newText);
fw.close();
System.out.println("File updated successfully.");
} catch (IOException e) {
System.out.println("An error occurred while updating the file.");
}
}
private static void deleteFile(String fileName) {
File file = new File(fileName);
if (file.delete()) {
System.out.println("File deleted successfully.");
} else {
System.out.println("Failed to delete the file.");
}
}
}
Comments
Post a Comment