/media/sda-magnetic/david/Dok-15-2023-11-27/fernuni-hagen/cs-i-ii/old-cs-2-03/java-new/2020-11-23/MyTreeFileProg.java


import java.io.*;

class MyTreeFileProg {
    public static void main (String [] args) {
        try {
            if (args[0].equals("save")) {
                BinaryTree root = new BinaryTree (args[2]);
                int i;
                
                for (i = 3;  i < args.length;  i++)
                    root.insertBinaryTree (args[i]);
                root.printBinaryTree();
                try {
                    OutputStream os = new FileOutputStream (args[1]);
                    ObjectOutputStream oos = new ObjectOutputStream(os);
                    oos.writeObject (root);
                    oos.close();
                }
                catch (IOException e) {
                    System.out.println ("We have a file problem");
                }
            }
            else if (args[0].equals ("read")) {
                try {
                    InputStream is = new FileInputStream (args[1]);
                    ObjectInputStream ois = new ObjectInputStream (is);
                    BinaryTree root = (BinaryTree) ois.readObject();
                    root.printBinaryTree();
                }
                catch (FileNotFoundException e) {
                    System.out.println ("We have a file error");
                }
                catch (IOException e) {
                    System.out.println ("We have a file error");
                }            
                catch (ClassNotFoundException e) {
                    System.out.println ("We have a file error");
                }            

            }
        }
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println ("usage: ");
            System.out.println ("MyTreeFileProg write fname data1 data2 ...");
            System.out.println ("MyTreeFileProg read fname");
        }
    }
    
    static class BinaryTree {
        BinaryTree l;
        BinaryTree r;
        String v;
        
        BinaryTree (String v) {
            this.v = v;
            this.l = null;
            this.r = null;
        }
        
        void saveBinaryTree (String fname) {
        }
        
        void insertBinaryTree (String v) {
            if (this.v.compareTo(v) < 0) {
                if (this.l == null)
                    this.l = new BinaryTree (v);
                else
                    this.l.insertBinaryTree (v);
            }
            else {
                if (this.r == null)
                    this.r = new BinaryTree (v);
                else
                    this.r.insertBinaryTree (v);
            }
        }
        
        void printBinaryTree () {
            if (this.l != null)
                this.l.printBinaryTree();
            System.out.println (this.v);
            if (this.r != null)
                this.r.printBinaryTree();
        }
    }
}