每行写入新的 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 行。因此,我不能简单地附加每个条目。

有更好的方法吗?

非常欢迎提示和技巧。 此外,我试过几个作家: - CSV 写入 - BufferedWriter - 文件编写器

还检查了 Whosebug 上的其他问题... 似乎无法让它发挥作用。谢谢!

更新:

问题得到解答!最终代码:

 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();
        }
    }
}

However, when I open the CSV file, it seems like it is written reversed. Excel first complains about the amount of rows. However, only the last row of my original dataset shows.

我认为这可能是因为缺少 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();
    }
}