Reputation: 654
I have a simple question that I could not figure out how to solve. I run an algorithm on different instances, and want to output the results into the same Excel file.
As an toy example, I wrote the following code, but it does not work properly.
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();
}
There are several issues obviously, but I receive the null point exception. I would really appreciate if someone could give me a hint / direction.
Upvotes: 1
Views: 1806
Reputation: 182
you are getting null pointer exception because,if file is available then go to else condition and there id no initialization for filewriter.you don't need to use two writer.here i am posting some code let me know if it helps.
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();
}
Upvotes: 1