[Java] 纯文本查看 复制代码 public class Test2 {
public static void main(String[] args) throws Exception {
//1.定义一个集合用于存储5条数据;
LinkedList<String> dataList = new LinkedList<>();
//2.用于从文件中取数据.将数据按顺序放入集合中.
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
String line;
while((line = br.readLine()) != null){
dataList.add(line);
}
System.out.println(dataList+"="+dataList.size());
br.close();
if(dataList.size()<5){
//4.获取需要存储的
String words = getWords();
dataList.addFirst(words);
//5.用于将数据按时间顺序依次存储到文件中
BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"));
//6.将集合中排好序的5条数据依次写入文件中.
for(int i = 0;i < dataList.size(); i++){
bw.write(dataList.get(i));
if(i != 4) bw.newLine(); //如果不是第五条数据那么就换行.
}
bw.close();
}else {
System.out.println("已达到文件最大存储长度.");
}
}
/**获取输入的字符串*/
private static String getWords() {
Scanner scanner = new Scanner(System.in); // 1.要求用户输入一句话
System.out.println("请输入字符串: ");
while (true) {
String words = scanner.nextLine();
if ("".equals(words)) {
System.out.println("输入字符串为空,请重新输入: ");
continue;
}
return words;
}
}
}{:7_413:} |