【问题标题】:Append at end of line in CSV file - Java在 CSV 文件的行尾追加 - Java
【发布时间】:2018-06-05 19:23:44
【问题描述】:

如果有匹配项,我想使用 Java 在 CSV 文件的行尾添加一个 ID。

这是我的代码的样子:

        String tempFile = "/C:/Users/chid.kulkarni/Desktop/JSON_CSV/temp.csv";
        File oldFile = new File(filepath);
        File newFile = new File(tempFile);
        String url1 = "";
        String Desc = "";

        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("[,\n]");

        while(x.hasNext())
        {
            url1 = x.next();
            Desc= x.next();

            if(url1.equals(editTerm))
            {
                System.out.println("Found!!, URL:"+url1);
                System.out.println("Edit_term:"+editTerm);
            }
        }
        }

        catch(Exception e)
        {
            System.out.println(e);
        }

输入

editTerm : www.airbnb.com

CSV 文件

URL                 Desc            
www.google.com     searches web
www.airbnb.com     House rentals
www.gmail.com      email application

所需的输出:如果 URL (www.airbnb.com) == editTerm (www.airbnb.com)

URL                 Desc               ID
www.google.com     searches web
www.airbnb.com     House rentals       100001
www.gmail.com      email application

我如何做到这一点?

我看过关于添加整列的博客/tuts。就我而言,我只想将 id 添加到特定行,而不是附加整个列。

【问题讨论】:

  • 实际上,你正在做的添加一列,只是在某些记录上有一个空白/空值

标签: java file csv


【解决方案1】:

我修改了 try-catch 块中的代码并获得了所需的输出。这个版本专门为editTerm写了“100001”的Id值。您可以稍后添加一个函数来检索特定于 editTerm 的 targetId。

我必须去掉“Desc”的最后一个字符,它会导致换行。

    String targetId = "100001";
    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("[,\n]");
        x.hasNext();
        url1 = x.next();
        Desc= x.next();
        Desc = Desc.substring(0,Desc.length()-1);
        pw.write(url1+","+Desc+",ID\n");
        while(x.hasNext())
        {
            url1 = x.next();
            Desc= x.next();
            Desc = Desc.substring(0,Desc.length()-1);
            pw.write(url1+","+Desc);
            if(url1.equals(editTerm))
            {
                System.out.println("Found!!, URL:"+url1);
                System.out.println("Edit_term:"+editTerm);
                //targetId = findTargetId(editTerm);// id finder function 
                pw.write(","+targetId);
            }
            pw.write("\n");
        }
        pw.close();
    }
    catch(Exception e)
    {
        System.out.println(e);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 2011-08-19
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    相关资源
    最近更新 更多