首页 > 解决方案 > 如何根据提供的值删除 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

解决方案


您得到的错误是java.util.NoSuchElementException在读取文件时。
这是由于连接了 2 行。
2018042316230011333第 5 行被解释为 traceID。
下一个字段 (ggg) 被解释为连续的 animalID。
因此,最后一行的最后一个字段被认为是 wayToTrade。然后,尝试读取最终的 traceID,您会收到错误消息。

也许最好逐行读取文件,将其拆分为其字段并跳过该行,以防第一个字段等于指定的 removeTerm。


推荐阅读