java - 从java中的文件中按id删除
问题描述
我的代码从文件中找到用户的 id 并将其放入数组中,但它不会从文件中删除该行。我想问题出在这个循环中(for(Object str:lines)),因为我的另一个类被称为“adh”,其中getter&setter和字符串functinos但是每当我将对象更改为str时它不会让我
public static void name_search() throws IOException, FileNotFoundException{
Adherent adh = new Adherent();
Scanner input= new Scanner(System.in);
String id;
System.out.println("Give ID: ");
id = input.nextLine();
File db = new File("adherent_db.txt");
BufferedReader reader = new BufferedReader(new FileReader(db));
String currentLine;
boolean first = false;
String[] fields = new String[0];
List<String> lines = new ArrayList<String>();
while((currentLine = reader.readLine()) !=null) {
if(!first) {
fields = currentLine.split(",");
first = true;
}
else {// only if both of the user's inputs (name and surname) match a contact then i add this contact's info to an array
String[] info=currentLine.split(",");
if(info[0].equals(id)) {
System.out.println("----There is a contact for the information you gave----");
for (int i = 0; i < fields.length; i++ ) {
System.out.println(info[i]);
}
//contact_change(currentLine);
lines.add(currentLine);
}
}
}
System.out.println("-------------------");
reader.close();
for(Object str:lines){//for every contatc that i found that is a match
contact_delete(str.toString());
}
}
public static void contact_delete(String line) throws IOException, FileNotFoundException{
File tempDB = new File("adherent_db_temp.txt");
File db = new File("adherent_db.txt");
BufferedReader reader1 = new BufferedReader(new FileReader(db));
String currentLine1;
boolean first = false;
String[] fields = new String[0];
BufferedWriter writer = new BufferedWriter(new FileWriter(tempDB));
while((currentLine1 = reader1.readLine()) !=null) {
if(!first) {
fields = currentLine1.split(",");
writer.write(currentLine1 + "\n");
first = true;
}
else if(!currentLine1.equals(line)){//if the current line in the reader is not the one we want to delete we write it to the temp file
writer.write(currentLine1 + "\n");
}
}
reader1.close();
writer.close();
db.delete();//we delete the original file
tempDB.renameTo(db);//we rename the temporary file to the original file's name
System.out.println("Information was valid, deletion completed successfully");
}```
解决方案
推荐阅读
- swift - 如何在构建阶段脚本中出现致命错误
- javascript - 快速服务器中的无限参数
- arrays - 将包含字符串的变量添加到数组不起作用
- jsp - 如何 servlet println(); 标签
- java - 如何在 android 中使用 NumberFormat 和 2 路数据绑定?
- deep-learning - colab找不到YOLOv3的权重文件
- c++ - 架构 x86_64 的未定义符号:leveldb::Comparator 的 typeinfo"
- c# - 在服务器 2016(本地)上安装 windows-service 失败
- html - 容器中的两个整页列
- extjs - 使用 Sencha Architect 在 extjs 中存储 REST API Url 的最佳实践