例:从键盘上读取数据,并写入到一个文件中。输入quit则表示退出,保留过去的历史数据。
public class Test {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
try (
Writer writer = new FileWriter("a.txt")
) {
String str = "";
while (true) {
str = sc.nextLine();
if ("quit".equals(str))
break;
writer.write(str + "\n");
}
}
sc.close();
try (
Reader r = new FileReader("a.txt")
) {
StringBuilder sb = new StringBuilder();
int kk = 0;
while ((kk = r.read()) > -1) {
if (kk != '\n') {
sb.append((char) kk);
} else {
System.out.println(sb);
sb.delete(0, sb.length());
}
}
}
}
}