【发布时间】:2021-04-06 20:02:18
【问题描述】:
我有一个基本上模仿数据库的 csv 文件,如果 csv 文件包含我提供的用户名输入,我的目标是从该 csv 中删除一行
当前的 csv 文件是:
Jack chan,customer,jack@yorku.ca,jack12,3144134414,13 Arboretum,user2
Donald tusk,customer,donald@yorku.ca,donald1,1213141114,14 Arboretum,user3
tom jack,customer,tom11@yahoo.com,tom44,131344122,14 wells st,user34
jack,parking officer,12rfw@hmail.com,jack,12131131134,12ddcscs,peo1
jewel khan,parking officer,jkhan@hotmail.com,jwel12,2131412141,12 wliis str,peo2
shane li,parking officer,shane@gmail.com,shaneli,1343513414,13 mac st,peo33
james chang,parking officer,james15@gmail.com,james12,31452434114,13 chang st,peo77
我的目标是使用他的用户名“shaneli”删除 say Shane li 的行,而不会对其他数据造成任何更改。但我当前的代码不会导致文件的其他数据发生变化
预期的输出 csv 文件是带有 shaneli 的行被删除,而其他行保持不变:
Jack chan,customer,jack@yorku.ca,jack12,3144134414,13 Arboretum,user2
Donald tusk,customer,donald@yorku.ca,donald1,1213141114,14 Arboretum,user3
tom jack,customer,tom11@yahoo.com,tom44,131344122,14 wells st,user34
jack,parking officer,12rfw@hmail.com,jack,12131131134,12ddcscs,peo1
jewel khan,parking officer,jkhan@hotmail.com,jwel12,2131412141,12 wliis str,peo2
james chang,parking officer,james15@gmail.com,james12,31452434114,13 chang st,peo77
这是我拥有的代码 java 代码,我需要一个 java 解决方案:
private static String userPath = "/CSVs/database.csv";
public void removeUser(String name,String userType,String email,String userName,String phoneNumber,String address,String password) {
// FIX THIS
String tmpFile = "tmp.csv";
// String target1 = ""; String target2 = ""; String target3 = ""; String target4 = ""; String target5 = "";String target6 = "";String target7 = "";
String target = "";
File oldFile = new File(userPath);
File newFile = new File(tmpFile);
System.out.println(userName);
try {
FileWriter fw = new FileWriter(tmpFile, true);
BufferedWriter bfw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bfw);
x = new Scanner(new File(userPath));
x.useDelimiter("[,\n]");
while (x.hasNext()) {
target = x.next();
if (!target.equals(userName)) {
pw.printf("%s,%s,%s,%s,%s,%s,%s\n", name, userType,email,userName,phoneNumber,address,password);
// pw.println(target + "," + target + "," + target + "," + target + "," + target + "," + target + "," + target);
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dmp = new File(userPath);
newFile.renameTo(dmp);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
请指教 提前致谢!!
【问题讨论】: