如何从 Java 中的文件二叉搜索树加载数据?

How to load data from file binary search tree in Java?

我使用读写从树加载和保存文件。为什么当我将员工保存到记事本时可以正常工作。但是当我运行时,我无法再次将它加载到节点中以显示它。有谁能够帮助我?我的读取功能有问题吗?我不知道如何从文件 txt 读取数据到树并在我 运行.

时加载它
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.Serializable;

import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.Vector;

class Employee implements Comparable<Employee>, Serializable {
    private static final long serialVersionUID = 1L;

        private int ID;
        private String name;
        String  address;
        public Employee getName;

        Employee(int emp_ID, String emp_name, String emp_address){
            ID = emp_ID;
            name = emp_name;
            address = emp_address;
        }
        public void print(){
            System.out.println(ID);
            System.out.println(name);
            System.out.println(address);
        }
        @Override
        public String toString() {
            return ID + "-" + name + "-" + address;
         }

         public int getID ( )
         {
             return ID;
         }

         public void setID (int emp_ID)
         {
             ID = emp_ID;           
         }  

         public String getName ( )
         {
             return name;
         }

         public void setName (String emp_Name)
         {
             name = emp_Name;           
         }

         @Override
         public int compareTo(Employee o) {     
            return 0;
         }

         public void input() {
            System.out.print("Please input an Employee \n");
            Scanner myScanner = new Scanner(System.in);
            System.out.println("Please input an Employee ID");
            ID = myScanner.nextInt();
            myScanner.nextLine();
            System.out.println("Please input an Employee Name");
            name = myScanner.nextLine();
            System.out.println("Please input an Employee Address");
            address = myScanner.nextLine();
          }
    }
 }

 /* Class BST */
 class BST
 {
     private Node root;

     /* Constructor */
     public BST()
     {
         root = null;
     }
     /* Function to check if tree is empty */
     public boolean isEmpty()
     {
         return root == null;
     }
     /* Functions to insert data */
     public void insert(Employee emp)
     {
         root = insert(root, emp);
     }
     /* Function to insert data recursively */
     private Node insert(Node node, Employee emp)
     {
         if (node == null)
             node = new Node(emp);
         else
         {
             if (emp.getID() <= node.getID())
                 node.left = insert(node.left, emp);
             else
                 node.right = insert(node.right, emp);
         }
         return node;
     }
     /* Functions to delete data */

     /* Functions to count number of nodes */

     /* Functions to search for an element */

     /* Function to search for an element recursively */

     /* Function for inorder traversal */
     public void inorder()
     {
         inorder(root);
     }
     private void inorder(Node r)
     {
         if (r != null)
         {
             inorder(r.getLeft());
             System.out.print(r.getData() +" ");
             inorder(r.getRight());
         }
     }
     /* Function for preorder traversal */
     public void preorder()
     {
         preorder(root);
     }

     private void preorder(Node r)
     {
         if (r != null)
         {
             System.out.print(r.getData() +" ");
             preorder(r.getLeft());             
             preorder(r.getRight());
         }
     }
     /* Function for postorder traversal */
     public void postorder()
     {
         postorder(root);
     }

     private void postorder(Node r)
     {
         if (r != null)
         {
             postorder(r.getLeft());             
             postorder(r.getRight());
             System.out.print(r.getData() +" ");
         }
     }

     public static int Read() {
         int count=0;
         try{
             Vector<Employee> vector = new Vector<Employee>();
             FileInputStream saveFile = new FileInputStream("D:/info.txt");
             ObjectInputStream save;
             try{
                 for(;;){
                     save = new ObjectInputStream(saveFile);
                     Employee emp = (Employee) save.readObject();
                     vector.add(emp);
                     count++;
                 }
             }catch(EOFException e){
                 //e.printStackTrace();
             }
             saveFile.close(); 

         }catch(Exception exc){
             exc.printStackTrace();
         }
         return count;
     }

     public void Write(Employee mm) {
         try
           {
             FileOutputStream fileOut = new FileOutputStream("D:/info.txt",true);
             ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fileOut));

             out.writeObject(mm);            
             out.close();
             fileOut.close();
             System.out.println("Serialized data is saved in info.ser");
           }catch(IOException i)
           {
               //i.printStackTrace();
           }
     }
 }

 /* Class BinarySearchTree */
 public class Binary
 { 
    public static void main(String[] args)
    {    
        Employee emp = null;

        int ID = 0;

        String name = null;
        int uID = 0;
        String address = null;
        Scanner scan = new Scanner(System.in);

        /* Creating object of BST */
        BST bst = new BST(); 

        System.out.println("Binary Search Tree Test\n");          
        char ch;
        /*  Perform tree operations  */
        do    
        {
            System.out.println("\nBinary Search Tree Operations\n");
            System.out.println("1. insert ");
            int choice = scan.nextInt();            
            switch (choice)
            {
            case 1 : 
                System.out.print("Please input an Employee \n");

                System.out.println("Please input an Employee ID");
                ID = scan.nextInt();
                scan.nextLine();
                System.out.println("Please input an Employee Name");
                name = scan.nextLine();
                System.out.println("Please input an Employee Address");
                address = scan.nextLine();
                emp = new Employee(ID,name,address);
                bst.insert(emp);
                bst.Write(emp);
                break;                          
            default : 
                System.out.println("Wrong Entry \n ");
                break;   
            }
            /*  Display tree  */ 
            System.out.print("\nPost order : ");
            bst.postorder();
            System.out.print("\nPre order : ");
            bst.preorder();
            System.out.print("\nIn order : ");
            bst.inorder();

            System.out.println("\nDo you want to continue (Type y or n) \n");
            ch = scan.next().charAt(0);                        
        } while (ch == 'Y'|| ch == 'y');               
    }    
 }

" 我不知道如何从文件 txt 中读取数据到树中并在我 运行 时加载它。"

看来您只是想将 BST 写入 .txt 文件,然后从该 .txt 文件中读取以构建 BST?

读取和写入方法必须相互一致(如何读取文件取决于写入 .txt 文件的格式):

将 BST 写入 .txt 文件的示例:

public static void main() {
    BST tree = //constructed BST
    PrintStream output = new PrintStream(new File(//name of file to write to));
    tree.write(output); // to write the tree to a file
    FileInputStream input = new FileInputStream(//file name goes here);
    tree.read(input); // to construct the tree from a file
}

所以写成格式的例子:


等...

    public void write(PrintStream output) {
        write(overallRoot, "", output);
    }

    private void write(TreeNode root, String code, PrintStream output) {
        if(root != null) {
            if(root.left == null && root.right == null) {
                output.println(root.data + "\n");
            }
            // recursive-case 
            write(root.left, output);
            write(root.right, output);
        }
    }

然后如果您想从该格式的文件中读取...

public void read(FileInputStream input) {
    TreeNode node = new TreeNode(input.nextLine()); //read from file line by line
    tree.insert(node); // use a BST insert method to build the tree node by node
}

希望对您有所帮助。