簡體   English   中英

每行寫入新的CSV文件(JAVA)

[英]Writing per line new CSV File (JAVA)

我有以下代碼:

public static void main(String[] args) throws IOException {
        //File being read:
        String fileName = "src/data/Belgium.csv";


    String[] nextLine;

    try (CSVReader reader = new CSVReader(new FileReader(fileName), ',', '"', 1)) {


        while ((nextLine = reader.readNext()) != null) {

            for (String line : nextLine) {
                //NewFile
                //When 2nd parameter - ture, it gets so big, that excel can't handle it anymore...
                FileWriter writer = new FileWriter("src/dataNew/BelgiumNew1.csv", true);

                line = line.replaceAll("T", " ");
                line = line.replaceAll("Z", "");
                line = line.replaceAll("ActualGenerationPerUnit.mean", "");
                line = line.replaceAll("Plantname:", "");
                //Escaping curly braces is a must!
                line = line.replaceAll("\\{", "");
                line = line.replaceAll("\\}", "");

                writer.append(line);
                writer.flush();
                writer.close();

                System.out.println(line);
            }
        }System.out.println("Successfully written");
    }
}

在控制台中,使用System.out.println(line)輸出的代碼為我提供了正確的輸出。 但是,當我打開CSV文件時,它似乎是反向寫入的。 Excel首先抱怨行數。 但是,僅顯示原始數據集的最后一行。 數據集(以一種低效的方式進行了預處理)包含1000多個行。 因此,我不能簡單地附加每個條目。

有更好的方法嗎?

提示和技巧非常受歡迎。 更進一步,我嘗試了一些編寫器:-CSVwrite-BufferedWriter-FileWriter

還檢查了Stackoverflow上的其他問題...似乎無法使其正常工作。 謝謝!

更新:

問題得到解答! 最終代碼:

 public static void main(String[] args) throws IOException {
    //File being read:
    String fileName = "src/data/Belgium.csv";

    //When 2nd parameter - ture, it gets so big, that excel can't handle it anymore...
      FileWriter writer = new FileWriter("src/dataNew/BelgiumNew5.csv", true);


    String[] nextLine;

    try (CSVReader reader = new CSVReader(new FileReader(fileName), ',', '"', 1)) {

        while ((nextLine = reader.readNext()) != null) {

            for (String line : nextLine) {

                line = line.replaceAll("T", " ");
                line = line.replaceAll("Z", "");
                line = line.replaceAll("ActualGenerationPerUnit.mean", "");
                line = line.replaceAll("Plantname:", "");
                //Escaping curly braces is a must!
                line = line.replaceAll("\\{", "");
                line = line.replaceAll("\\}", "");

                writer.append(line);
                writer.append(System.lineSeparator());
                System.out.println(line);


            }
        }System.out.println("Successfully written");
        }catch(Exception e){
        e.printStackTrace();
    }finally {
        if (writer != null){
            writer.flush();
            writer.close();
        }
    }
}

但是,當我打開CSV文件時,它似乎是反向寫入的。 Excel首先抱怨行數。 但是,僅顯示原始數據集的最后一行。

我認為這可能是由於CSV行之間缺少換行符引起的。

實際上,當您在文件中寫一行時,您不會寫換行符。 您可以在每個讀取行之后編寫它: writer.append(System.lineSeparator())

作為旁注:

1)為什么不在循環之前將其移動(否則效率較低):

FileWriter writer = new FileWriter("src/dataNew/BelgiumNew1.csv", true);

2)您不應該在每個讀取行刷新並關閉文件,因為它效率較低:

writer.append(line);
writer.flush();
writer.close();
System.out.println(line);

應該足夠了:

writer.append(line);
System.out.println(line);

保持:

writer.flush();
writer.close();

finally聲明中,例如:

FileWriter writer = new FileWriter("src/dataNew/BelgiumNew1.csv", true);

try{
  // all your operations to handle the file
}

catch(Exception e){
  // your exception handling
}

finally{
   if (writer!=null){
      writer.flush();
      writer.close();
   }
}

編輯以回答評論:

如果您覺得輸出文件包含多組記錄,則它可能與您使用的FileWriter的附加模式有關。

替換為:

FileWriter writer = new FileWriter("src/dataNew/BelgiumNew1.csv", true);

以此不使用此模式:

FileWriter writer = new FileWriter("src/dataNew/BelgiumNew1.csv", false);

我看到您正在使用opencsv讀取csv文件。 除了來自davidxxx的正確答案之外,如果您使用opencsv中的CSVWriter寫入文件,則可以簡單地編寫代碼。 下面是一個示例:

import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class Example1 {

    public static void main(String args[]) throws IOException {                              
         String fileName = "src/data/Belgium.csv";
         CSVReader reader = new CSVReader(new FileReader(fileName), ',','"',1);
         List<String[]> lines = reader.readAll();         
         CSVWriter writer = new CSVWriter(new FileWriter("src/data/BelgiumNew1.csv",false), ',');
         for(String[] row : lines){
             for(int i = 0; i< row.length; i++){
                row[i] = row[i].replaceAll("T", " ")
                         .replaceAll("Z", "z")
                         .replaceAll("ActualGenerationPerUnit.mean", "")
                         .replaceAll("Plantname:", "")
                         .replaceAll("\\{", "")
                         .replaceAll("\\}", "");                 
             }
             writer.writeNext(row);
         }
         writer.flush();
         writer.close();
    }
} 

暫無
暫無

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

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