【问题标题】:Writing per line new CSV File (JAVA)每行写入新的 CSV 文件(JAVA)
【发布时间】:2017-05-04 13:17:35
【问题描述】:

我有以下代码:

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

【问题讨论】:

    标签: java csv filewriter writer


    【解决方案1】:

    但是,当我打开 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);
    

    【讨论】:

    • 但是...标题(列名消失了,由于某种原因,我的行数增加了近 3 倍...)
    • 不客气 :) 关于行数要大得多,不知道。在显示的代码中,除了编写器的附加模式之外,没有什么可以解释的。将其更改为 true 并重试。关于列标题,当您阅读带有 CSV 库的 CSV 文件时,预计您不会阅读标题。或者,您使用的库允许检索标题,在这种情况下,您可以使用它。否则,只需在之前创建带有标题的行以将内容附加到文件中。我通过添加编辑了我的答案。
    • 天哪!有效!不得不写一个新文件!非常感谢你!我永远感激不尽!已经疯了一个星期了...
    【解决方案2】:

    我看到您正在使用 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();
        }
    } 
    

    【讨论】:

    • 这是一种看待它的方式!谢谢!还将尝试解析另一个数据集...我尝试了嵌套的 for 循环,但没有成功。因此最终以这种方式编码......
    猜你喜欢
    • 2017-02-04
    • 2014-05-10
    • 2023-03-13
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    相关资源
    最近更新 更多