今晚的月色温柔

导航

文件的读写

【问题描述】从终端输入5行数据,写入文件,然后读出后打印出来
【输入形式】
【输出形式】
【样例输入】

a
b
c
d
e

【样例输出】

a
b
c
d
e

【样例说明】
【评分标准】

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class App {
public static void saveToFile(String fname) {
try {
PrintWriter pw = new PrintWriter(new FileWriter(fname));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int i = 1; i <= 5; i++) {
pw.println(br.readLine());
}
pw.println();
br.close();
pw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void readFromFile(String fname) {
try {
BufferedReader br = new BufferedReader(new FileReader(fname));
String line;
while (true) {
line = br.readLine();
if (line == null)
break;
System.out.println(line);
}
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void main(String[] args) {
saveToFile("file.txt");
readFromFile("file.txt");
}
}

 

posted on 2020-12-12 17:01  1022  阅读(252)  评论(0编辑  收藏  举报