Java完整代码编写程序按行读取键盘输入文本(古诗一首,内容不限),然后按行写入”古诗名称.txt”文件中,要求每行前面添加一个行序号,并在文件最后一行写入自己名字
时间: 2024-03-11 18:47:44 浏览: 57
好的,以下是Java代码:
```java
import java.io.*;
public class Main {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = null;
try {
// 从键盘读取文本
String poem = "";
System.out.println("请输入古诗:");
while (true) {
String line = reader.readLine();
if (line.equals("EOF")) break;
poem += line + "\n";
}
// 写入文件
writer = new BufferedWriter(new FileWriter("古诗名称.txt"));
String[] lines = poem.split("\n");
for (int i = 0; i < lines.length; i++) {
String line = i + 1 + ". " + lines[i] + "\n";
writer.write(line);
}
writer.write("——by your name");
System.out.println("写入成功!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) writer.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
这个程序会让用户从键盘输入古诗,直到输入 "EOF" 结束输入。然后程序会按行写入文件,并在每一行前加上行号。最后一行会写入用户的名字。
阅读全文