gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:27:09 25 4
gpt4 key购买 nike

我有一个简单的问题,我不知道如何解决。我在不同的实例上运行算法,并希望将结果输出到同一个 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();
}

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

最佳答案

您收到空指针异常,因为如果文件可用,则转到其他条件,并且文件写入器没有初始化。您不需要使用两个写入器。这里我发布了一些代码,让我知道它是否有帮助.

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

}

关于java - 如何使用 FileWriter 写入同一个 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58313994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com