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 14:45:16 浏览: 72
Here's an implementation in Java:
```
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class ConversationReader {
private static final String FILE_PATH = "conversation.txt";
public static void main(String[] args) throws IOException {
ConversationReader reader = new ConversationReader();
reader.readWithScanner();
reader.readWithBufferedReader();
reader.readWithBufferedReaderAndPause();
}
public void readWithScanner() throws IOException {
File file = new File(FILE_PATH);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
}
public void readWithBufferedReader() throws IOException {
File file = new File(FILE_PATH);
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
public void readWithBufferedReaderAndPause() throws IOException {
File file = new File(FILE_PATH);
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
int lineCount = 0;
while ((line = reader.readLine()) != null) {
lineCount++;
System.out.println(line);
if (lineCount % 2 == 0) {
System.out.println("Press enter to continue...");
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
}
}
reader.close();
}
}
```
The `readWithScanner()` method reads the file using a `Scanner`, while the `readWithBufferedReader()` method reads the file using a `BufferedReader`. Both methods simply loop through the lines of the file and print them to the console.
The `readWithBufferedReaderAndPause()` method reads the file using a `BufferedReader` and pauses after every two lines. It keeps track of the line count and waits for the user to press enter before printing the next two lines. This continues until all the lines have been printed.
Note that this implementation assumes that the `conversation.txt` file is in the same directory as the Java file. You may need to modify the `FILE_PATH` constant if your file is located elsewhere.
阅读全文