Question

I can't figure out how to write a Binary Search Tree to file recursively. I open a BufferWriter with the file to wrtie too, in the Tree class. I then send the BufferWriter to the Node class to traverse the tree inorder and write to file. But it doesn't work.

public void write(String filePath)
{
  if(root != null) {
    try {
      BufferedWriter out = new BufferedWriter(new FileWriter(filePath));
      root.write(out);
    } catch (IOException e) {
    }
  }
}

public void write(BufferedWriter out)
{
    if (this.getLeft() != null) this.getLeft().write(out);
    out.write(this.data());
    if (this.getRight() != null) this.getRight().write(out);
}
Was it helpful?

Solution

That doesn't look so bad! Could it be you're just missing the close() on your BufferedWriter when you're done? The file will likely not be written correctly if there's no close.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top