Create a new class that reads the conversation.txt line by line and prints it to the console. In this class you should implement two different methods to read the file: 1. Implement a method using a Scanner that reads the file. (Successfully printing file content to Console: 1P) 2. Implement a method that uses a BufferedReader to read the file. (Successfully printing file content to Console: 1P) Finally, alter the second method that reads the file line by line using a BufferedReader. After printing the first two lines, make your programme wait for the user to press enter before printing the next two lines. Continue this until all the lines are printed. Once the end of the file is reached, the programme should terminate so that when the user presses enter again, nothing bad happens.
时间: 2023-12-03 16:43:58 浏览: 33
Here's the implementation:
```java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class ConversationReader {
public static void main(String[] args) {
// Reading file using Scanner
readWithScanner("conversation.txt");
// Reading file using BufferedReader
readWithBufferedReader("conversation.txt");
// Reading file using BufferedReader and waiting for user input
readWithBufferedReaderAndPause("conversation.txt");
}
private static void readWithScanner(String fileName) {
try (Scanner scanner = new Scanner(new File(fileName))) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void readWithBufferedReader(String fileName) {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void readWithBufferedReaderAndPause(String fileName) {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
int lineNumber = 0;
boolean paused = false;
while ((line = reader.readLine()) != null) {
lineNumber++;
System.out.println(line);
if (lineNumber % 2 == 0) {
paused = true;
}
if (paused) {
System.out.print("Press enter to continue...");
System.in.read();
paused = false;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
Explanation of the code:
- `readWithScanner` method reads the file using `Scanner` class and prints the content to the console.
- `readWithBufferedReader` method reads the file using `BufferedReader` class and prints the content to the console.
- `readWithBufferedReaderAndPause` method reads the file using `BufferedReader` class and prints the content to the console, but waits for user input after every two lines. This is achieved by keeping track of the line number and setting a flag to pause the output after every even line. The user is prompted to press enter to continue, and the flag is reset to resume the output.