Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
每行写入新的CSV文件(JAVA)_Java_Csv_Filewriter_Writer - Fatal编程技术网

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

每行写入新的CSV文件(JAVA),java,csv,filewriter,writer,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

我有以下代码:

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

还检查了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) 为什么不在循环之前移动它(否则效率较低):

2) 不应在每个读取行刷新并关闭文件,因为这样会降低效率:

FileWriter writer = new FileWriter("src/dataNew/BelgiumNew1.csv", true);
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();
    }
} 
导入com.opencsv.CSVReader;
导入com.opencsv.CSVWriter;
导入java.io.FileReader;
导入java.io.FileWriter;
导入java.io.IOException;
导入java.util.List;
公共课示例1{
公共静态void main(字符串args[])引发IOException{
String fileName=“src/data/belling.csv”;
CSVReader reader=new CSVReader(新文件读取器(文件名),,,,,,,,,1);
列表行=reader.readAll();
CSVWriter writer=newCSVwriter(新文件编写器(“src/data/BelgiumNew1.csv”,false),',');
用于(字符串[]行:行){
for(int i=0;i
但是…标题(列名不清晰,出于某种原因,我的行数几乎增加了3倍…)欢迎:)关于行数,行数要大得多,不知道。在显示的代码中,除了编写器的附加模式之外,没有什么可以解释这一点。请将其更改为true,然后重试。关于列标题,当您使用CSV库读取CSV文件时,预期您不会读取标题。或者,您使用的库允许检索标题,在这种情况下,您可以使用它。否则,只需在添加文件内容之前创建一行标题。我用adding.omg编辑了我的答案!成功了!必须编写一个新文件!非常感谢!永远感谢!已经疯狂了一周…这是一种看待它的方式!谢谢!威尔o尝试解析另一个数据集…我尝试了嵌套for循环,但没有成功。因此最终以这种方式编码。。。