java - 每行写入新的 CSV 文件 (JAVA)

标签 java csv filewriter writer

我有以下代码:

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写入 - 缓冲写入器 - 文件编写器

还检查了 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();
        }
    }
}

最佳答案

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

关于java - 每行写入新的 CSV 文件 (JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41223421/

相关文章:

MySQL select into outfile "file already exists"和 "file does not exist"对偶(?)案例

python - 计算(和写入)文本文件中每一行的词频

java filewriter写入实例的不完整数据

java - 如何在 ListView 中显示使用文件写入器保存的项目

JAVA正则表达式提取特殊字符后的字符串

java - 使用java swing实现滑动抽屉动画

java - Apache camel - 将文件写入 ftp 失败

php - 如何从 MySQL 表数据创建 Word 文档?

java - 在java中使用SuperCsv读取tsv文件时出现异常

java - Play!2.2.1 Java Ebean - Finder.select(String columns) 不起作用 : all the columns are selected