Can load in exactly same way: read root, read and attach left subtree, read and attach right subtree.
File operations are pretty straightforward:
// create a new input file with name fileName. DataInputStream inFile = new DataInputStream(new FileInputStream(fileName));
// read character from inFile and store in letter char letter = inFile.readChar();
// read string from inFile and store in contents String contents = inFile.readUTF();
// close file inFile.close(); // create a new output file with name fileName. DataOutputStream outFile = new DataOutputStream(new FileOutputStream(fileName));
// write character from letter onto outFile outFile.writeChar(letter);
// write string from contents onto outFile outFile.writeUTF(contents);
// close file outfile.close();These classes are found in package java.io, so you must include an import statement for them.
File operations can throw exceptions because not find file, hit end of file when reading, etc.! In Java, one must test for exceptions and provide code to execute when exceptions are raised.
Java file operations may raise exceptions of type IOException. Must surround code that may throw this exception by:
try {//code using files} catch (IOException exc) {//code to execute if exception raised}In the above, exc is a parameter of type IOException. You can send it a toString message to get info on what went wrong in the block that follows it.
You can either put all of the code into one single try-catch block or put each command that may raise the exception in such a block. You will get syntax errors if you do not surround these file messages with a try-catch block.
Your program should not just ignore these exceptions. At a minimum it should print out a message and return to a consistent state.