在CSV文件的末尾附加 - Java

时间:2018-06-05 19:23:44

标签: java file csv

如果匹配,我想在使用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

所需输出:如果网址(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

我如何实现这一目标?

我看过有关添加整个专栏的博客/评论。就我而言,我只想在特定行中添加一个id,而不是追加整个列。

1 个答案:

答案 0 :(得分:0)

我修改了try-catch块中的代码并实现了所需的输出。此版本专门为editTerm写入Id值“100001”。您可以稍后添加一个函数来检索特定于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);
    }