Write the while loop that reads each line from the console input stream and prints the line out to the file. Each line should be prepended with the count of the line number. in java
时间: 2024-01-06 22:04:56 浏览: 39
Here's an example of a Java while loop that reads each line from the console input stream, prepends the count of the line number, and prints the line out to a file:
```java
import java.io.*;
public class LineCounter {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
FileWriter writer = new FileWriter("output.txt");
int count = 1;
String line;
while ((line = reader.readLine()) != null) {
writer.write(count + ": " + line + "\n");
count++;
}
reader.close();
writer.close();
}
}
```
In this example, we create a `BufferedReader` to read input from the console, and a `FileWriter` to write output to a file named "output.txt". We initialize a `count` variable to 1 to keep track of the line number.
The while loop reads each line from the input stream using the `readLine()` method, and checks if the line is not `null`. If the line is not `null`, we write the line to the output file, with the line number prepended to the beginning of the line. We then increment the `count` variable to keep track of the line number for the next iteration of the loop.
Finally, we close both the input and output streams to release any system resources that were being used.