每行写入新的CSV文件(JAVA) [英] Writing per line new CSV File (JAVA)

查看:167
本文介绍了每行写入新的CSV文件(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行。因此,我不能简单地追加每一个条目。

The output of the code in my console, using System.out.println(line) gives me the correct output. 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. The dataset (which is preprocessed in an inefficient way), contains more than 1000 rows. Therefore, I can not simply append every single entry.

有更好的方法吗?

提示和技巧是非常受欢迎的。
另外,我已经尝试了几个作者:
- CSVwrite
- BufferedWriter
- FileWriter

Tips and tricks are very welcome. Furtermore, I have tried several writers: - CSVwrite - BufferedWriter - FileWriter

还检查了其他问题Stackoverflow ...
似乎无法使它工作。谢谢!

Also checked other issues on Stackoverflow... Can't seem to make it work. Thank you!

更新:

问题已解答!最终代码:

Question is answered! Final code:

 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首先抱怨行数。但是,
只显示我原始数据集的最后一行。

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行之间的字符。

I think that it is probably caused because a new line character between CSV rows is missing.

实际上,当您在文件中写入一行时,不会写新行字符。
您可以在每条读取行之后编写它: writer.append(System.lineSeparator())

Actually you don't write a new line character when you write a row in the file. You could write it : writer.append(System.lineSeparator()) after each read line.

作为附注:

1)为什么不在循环之前移动它(否则效率较低):

1) Why not moving it before the loop (otherwise it is less efficient) :

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

2)你不应该在每条读取线上刷新并关闭文件,因为效率较低:

2) You should not flush and close the file at each read line as it is less efficient :

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






编辑回答评论:


EDIT to answer to the comment :

如果您认为输出文件包含多组记录,则可能与<$ c的附加模式有关您使用的$ c> FileWriter 。

If you have the impression that the output file contains multiple set of records, it is probably related to the append mode of the FileWriter that you used.

替换为:

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

由此不使用此模式:

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

这篇关于每行写入新的CSV文件(JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆