本文使用流进行存储和读取,有兴趣深入研究的小伙伴去看看java io流
//写数据
public String writeTxt(String planId,String name){
try {
//如果文件存在,则追加内容;如果文件不存在,则创建文件
File f = new File("NameAndId.txt");
FileWriter fw = new FileWriter(f, true);
PrintWriter pw = new PrintWriter(fw);
//java数据,可以转成json字符串存储
String dataString = "{\"planId\":\""+planId+"\",\"name\":\""+name+"\"}";
pw.println(dataString);
pw.flush();
pw.close();
fw.close();
return "success";
} catch (IOException e) {
e.printStackTrace();
}
return "failure";
}
//读数据:获取本地文件中最后一行数据
public String readTxt() {
try {
String path = "NameAndId.txt";
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(path)), "UTF-8"));
String lineTxt = null;
List<String> list = new ArrayList<String>();
int count = 0;
// 逐行读取
while ((lineTxt = br.readLine()) != null) {
list.add(lineTxt);
}
System.out.println("这是最后一个"+list.get(list.size()-1));
br.close();
return list.get(list.size()-1);
} catch (Exception e) {
System.out.println(e);
}
return "failure";
}