package com.wr.demo;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class test05 {
public static void main(String[] args) throws FileNotFoundException {
// 用于存储用户输入的列表
List<String> fileContent = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
System.out.println("请输入多行字符串(以单行'#'结束输入): ");
// 循环获取用户输入
while (true) {
String line = scanner.nextLine();
if (line.equals("#")) {
break;
} else {
fileContent.add(line);
}
}
// 将用户输入的内容写入到文件中
try {
PrintWriter writer = new PrintWriter("output.txt", "UTF-8");
for (String str : fileContent) {
writer.println(str);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
throw new RuntimeException(e);
}
// 从文件中读取内容并输出到屏幕上
try {
BufferedReader reader = new BufferedReader(new FileReader("output.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
实验运行截图: