如何在Java中从文件二进制搜索树加载数据?

时间:2017-08-17 12:52:18

标签: java linked-list load binary-tree binary-search-tree

我使用读写来加载和保存树中的文件。为什么当我将员工保存到记事本时就是工作。但我无法再将其加载到节点中以便在运行时显示它。有谁能够帮我?我的阅读功能有问题吗?我不知道如何从文件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');               
    }    
 }

1 个答案:

答案 0 :(得分:0)

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

soo似乎你只是想把BST写成.txt文件,然后从那个.txt文件中读取来构建BST?

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

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

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
}

以格式写作的一个例子:


等...

{{1}}

然后如果你想用该格式读取文件......

{{1}}

我希望这会有所帮助。