簡體   English   中英

在 CSV 文件的行尾追加 - Java

[英]Append at end of line in CSV file - Java

如果有匹配項,我想使用 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);
        }

輸入

編輯條款: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 添加到特定行,而不是附加整個列。

我修改了 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);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM