如何使用 FileWriter 写入同一个 CSV 文件

How to write into the same CSV file with FileWriter

我有一个简单的问题,但我不知道如何解决。我 运行 一个算法在不同的实例上,并希望将结果输出到同一个 Excel 文件中。

作为玩具示例,我编写了以下代码,但它无法正常工作。

String DATADIR = "C:/Users/OneDrive/Desktop/";
for(int i =0; i<=2 ; i++){          
  File f = new File(DATADIR+ "myFile.csv"); // I first check if the file exists
  FileWriter mainWriter = null; // here there is a problem
    if(!f.exists() && !f.isDirectory()) { // If not, then I create the file
    FileWriter writer = new FileWriter(DATADIR+ "myFile.csv", true);
    mainWriter = writer; // I copy the file for the next iterations
    writer.write("This is my first line \n"); 
    writer.close();
    }else { //if file exists, then continue writing
        mainWriter.write(i+ "\n"); // as an trivial example, write the iterator
        mainWriter.close();
    }

显然有几个问题,但我收到了空点异常。如果有人能给我提示/方向,我将不胜感激。

你得到空指针异常是因为,如果文件可用然后转到其他条件并且没有为 filewriter.you 进行初始化不需要使用两个 writer.here 我正在发布一些代码让我知道是否有帮助。

String DATADIR = "C:/Users/OneDrive/Desktop/";
        for (int i = 0; i <= 2; i++) {
            File tmpDir = new File(DATADIR+" myFile.csv");
            if (!tmpDir.exists() && !tmpDir.isDirectory()){ //checking file availability
                tmpDir.createNewFile(); //create new file
            }
            FileWriter writer = new FileWriter(DATADIR+ "myFile.csv", true); //as mentioned if not available then create new file so here always available file
            if (i==0){
               writer.write("This is my first line \n"); //writing first line
                     }
            else {
                writer.write(i+ "\n"); //then appends all other data.
            }
            writer.close();

        }