views:

158

answers:

1

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

Any help would be great, Thanks.

+2  A: 

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.

Carl Smotricz
Yup, the close() was the problem thanks!
Thanks for the feedback, glad to help!
Carl Smotricz