In: Computer Science
how to read, write and append a text file using a switch case in java.I need help with the code.
Main.java
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.FileWriter;
import java.io.FileReader;
public class Main
{
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
System.out.println("1. Write to the file");
System.out.println("2. Append to the file");
System.out.println("3. Read from the file");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();
switch(choice){
case 1:
// Open the file.
PrintWriter write = new PrintWriter("demo.txt");
// Writing to the file
write.println("Atlantic");
// Close the file.
write.close();
break;
case 2:
// Open the file in append mode.
FileWriter fw = new FileWriter("demo.txt",true);
PrintWriter append = new PrintWriter(fw);
// Appending to the file
append.println("Southern");
// Close the file.
append.close();
break;
case 3:
// Open the file.
FileReader fr = new FileReader("demo.txt");
Scanner inFile = new Scanner(fr);
// Read lines from the file till end of file
while (inFile.hasNext())
{
// Read the next line.
String line = inFile.nextLine();
// Display the line.
System.out.println(line);
}
// Close the file.
inFile.close();
break;
default:
System.out.println("Invalid choice!");
}
}
}
demo.txt
Atlantic
Southern