Create a new class that writes to the included txt file. Use a BufferedWriter to write the following text to the file: What took you so long? Well, you know, Master, I couldn't find a speeder that I really liked... There he is. ...with an open cockpit and the right speed capabilities. If you spent as much time practicing your saber techniques as you did your wit, you'd rival Master Yoda as a swordsman. I thought I already did. Only in your mind, my very young apprentice. Make sure that all the line breaks are correct. Hint: You can access the file via its relative path by just stating its name: conversation.txt. No need to have the complete path to the file.
时间: 2023-12-03 14:45:15 浏览: 30
Here's a possible implementation:
```java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class ConversationWriter {
public static void main(String[] args) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("conversation.txt"));
writer.write("What took you so long?\n");
writer.write("Well, you know, Master, I couldn't find a speeder that I really liked...\n");
writer.write("There he is.\n");
writer.write("...with an open cockpit and the right speed capabilities.\n");
writer.write("If you spent as much time practicing your saber techniques as you did your wit, you'd rival Master Yoda as a swordsman.\n");
writer.write("I thought I already did.\n");
writer.write("Only in your mind, my very young apprentice.\n");
writer.close();
System.out.println("Conversation saved to file.");
} catch (IOException e) {
System.err.println("Failed to write conversation to file: " + e.getMessage());
}
}
}
```
This class creates a `BufferedWriter` that writes to the file `conversation.txt` (which should be in the same directory as the Java file). The `write` method is called multiple times to write each line of the conversation, including the correct line breaks (`\n`). Finally, the `close` method is called to flush any remaining buffered data and release the resources. If an exception occurs, an error message is printed to the console. If everything works as expected, a confirmation message is printed.