java - 如何根据提供的值删除 CSV 文件中的内容?
问题描述
我目前正在尝试解决这个问题,我似乎无法删除 csv 文件的特定内容。
package projectasdp;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Test {
private static Scanner x;
public static void main(String[] args) {
String filepath = "TradeDetails.txt";
String removeTerm = "3";
removeRecord(filepath, removeTerm);
}
public static void removeRecord(String filepath, String removeTerm) {
String tempFile = "temp.txt";
File oldFile = new File(filepath);
File newFile = new File(tempFile);
String animalID = "";
String seller = "";
String buyer = "";
String wayToTrade = "";
String tradeID = "";
try {
FileWriter fw = new FileWriter(tempFile, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
x = new Scanner(new File(filepath));
x.useDelimiter("[,\r\n]+");
while(x.hasNext()) {
animalID = x.next();
seller = x.next();
buyer = x.next();
wayToTrade = x.next();
tradeID = x.next();
if(!animalID.equals(removeTerm)){
pw.println(animalID + "," + seller + "," + buyer + "," + wayToTrade + "," + tradeID );
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filepath);
newFile.renameTo(dump);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error");
}
}
}
CSV:
0,Ann,Jesca,offonline,20180411091801
3,Dave,Dianna,online,20180418105901
6,Dianna,Flynn,offonline,20180418162304
25041019042018,Lex,Ada,online,20180419102911
123456,D,Lucasy,offonline,2018042316230011333,ggg,EEE,online,20190319135223
334,John,Malik,online,20190319135310
这里的想法是删除 ID 3 的所有信息,在本例中为3,Dave,Dianna,online,20180418105901
. 我已经用 removeTerm 变量指定了它。
到目前为止,我还没有设法让它工作,并且对于这个问题还有其他我可能不熟悉的解决方案,所以我非常感谢任何帮助。
解决方案
您得到的错误是java.util.NoSuchElementException
在读取文件时。
这是由于连接了 2 行。
2018042316230011333
第 5 行被解释为 traceID。
下一个字段 (ggg) 被解释为连续的 animalID。
因此,最后一行的最后一个字段被认为是 wayToTrade。然后,尝试读取最终的 traceID,您会收到错误消息。
也许最好逐行读取文件,将其拆分为其字段并跳过该行,以防第一个字段等于指定的 removeTerm。
推荐阅读
- mysql - 检查 MySQL 中 JSON 数据中是否存在值
- xamarin - Xamarin IOS 或 Xamarin Android 项目能否引用 .NET 5 或 .NET Core 项目
- reactjs - 从函数体而不是 useEffect(fn,[]) 获取数据时有什么缺点或问题?
- gatsby - Gastby 主页组件仅在 Prod 中的所有页面上双重渲染(不在本地/开发中)
- python - 条件语句和多个函数
- android - 将本机 AAR 导入本机 andorid - 无法访问的类错误
- javascript - 当导航栏定位时:已修复如何解决与其他组件重叠的问题?
- java - spring boot中如何避免篡改api响应
- c# - 将数据存储在范围服务(按请求)中以提高性能的缺点是什么
- docker - 了解 docker 日志