I have a tree setup. I am trying to save it into a txt file using a BufferedWriter. It creates the file, then it runs into a null pointer exception when my program first calls the write method of the BufferedReader(line 102), so I guess its not getting initialized properly? Note: "node" is just the payload of the root, I can print the tree using the same method, so the issue is not with the node variable.
public class TreeNode {
File file;
BufferedWriter writer;
FileWriter fw;
public void save() /// save tree into txt file
{
try
{
file = new File("save.txt");
if(!file.exists())
{
file.createNewFile();
}
fw = new FileWriter(file);
writer = new BufferedWriter(fw);
print();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void print() {
try
{
writer.write(node); //line 102
writer.newLine();
if (no != null)
{
no.print();
writer.newLine();
}
if (yes != null)
{
yes.print();
writer.newLine();
}
writer.flush();
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Error:
Exception in thread "main" java.lang.NullPointerException
at TreeNode.print(TreeNode.java:102)
at TreeNode.print(TreeNode.java:106)
at TreeNode.save(TreeNode.java:90)
at TreeNode.playagain(TreeNode.java:59)
at TreeNode.go(TreeNode.java:189)
at CelebrityGame.main(CelebrityGame.java:22)