我有一个简单的问题,无法解决。我在不同的实例上运行算法,并希望将结果输出到同一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进行初始化。您不需要使用两个writer。在这里,我发布一些代码让我知道是否有帮助。

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

        }

10-01 05:43
查看更多