Results 1 to 19 of 19
  1. #1
    vuzuggu is offline Member
    Join Date
    Oct 2011
    Posts
    19
    Rep Power
    0

    Default Saving Binary Tree to file

    I am trying to save a binary tree to file but cannot get it to work. It just creates an empty file.

    I have put all the code below and would appreciate if someone could give me a pointer.

    Java Code:
    static class Node {
    		public String question;    
    		public Node True;    
    		public String name;  
    		public Node False;    
    		public void branch()
            
    		{        
        		if(question != null) 		{                
        			input = terminal.readString(question + "\n");                        
                    if (input.contains("true"))                
                            True.branch();                
                    else                
                            False.branch();              
        		}        
        		else if(question == null) 	{            
                    input = terminal.readString("Is it a/an " + name + "?\n");                     
                    if(input.contains("true"))               
                    {  terminal.println("I win!"); }            
                    else  {                                            
                         terminal.println("I give up.\n");                
                         newName = terminal.readString("What were you thinking of?\n");                
                                            
                         newQuestion = terminal.readString("What is a question that you " + "would answer no to " + newName + ", but " + "yes to " + name + "?\n");                               
                         True = new Node();                
                         True.name = name;                
                         False = new Node();                
                         False.name = newName;                
                         name = null;              
                         question = newQuestion;                
                         terminal.println(newName + " has been added to the game.");            
                     }                     
         }          
       }
    	
    }
    	
    
    
    
    public static void main(String[] args) throws Exception {
    	 
    	 Node first = new Node();
    	 first.question = "Is it an animal?"; 
    	 first.True = new Node(); 
    	 first.True.name = "Elephant";
    	 first.False = new Node();
    	 first.False.name = "DVD"; 
    	 
    	 			do  { 
    	 					first.branch();
    	 					end = terminal.readString("Quit or play again?");
    	 				
    	 				}  while(end.equals("again"));
    	 					
    	 		FileWriter fstream = new FileWriter("C:\\Users\\Daniel\\My Documents\\College\\CS1011\\testfiles\\Binary.txt");
    		 	BufferedWriter out = new BufferedWriter(fstream);	
    		 			    
    		 	printInOrder(first, out);
    		 	out.flush();
    		 	out.close();	
    	 		terminal.println("The game has ended.");
    	 			
    	 		
    	}
    
    
    private static void printInOrder(Node first, BufferedWriter out) throws IOException {
    	
    	if (first != null) {
    		   out.write("helloworld!");
    	       printInOrder(first.True, out);
    	       System.out.println(first.True.name);
    	       out.newLine();
    	       printInOrder(first.False, out);
    	    }
    	       
    	    }
    	
    }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,421
    Rep Power
    25

    Default Re: Saving Binary Tree to file

    Have you tried debugging your code by adding printlns to see where the execution flow goes and to show the contents of all the variables you use. Print out a line every time you write it to the file. If there are no print outs, then your logic is not working. Print out the values of the variables that control when you write a line to see why the line is not being written.


    Your posted code does not compile. Impossible to test.
    Last edited by Norm; 12-14-2011 at 01:02 PM.

  3. #3
    vuzuggu is offline Member
    Join Date
    Oct 2011
    Posts
    19
    Rep Power
    0

    Default Re: Saving Binary Tree to file

    Sorry. Forgot to add the second file of code.

    I think I know what to do now. But I am having a hard time to find on google is how to navigate the whole way down a binary tree. IE start at root node then go all the way left until you get a null then work the way up so I can save all the nodes to a file?

  4. #4
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,526
    Blog Entries
    7
    Rep Power
    20

    Default Re: Saving Binary Tree to file

    Have you considered making your Node class Serializable? The serialization mechanism can store entire trees for you without any code implemented by you.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  5. #5
    vuzuggu is offline Member
    Join Date
    Oct 2011
    Posts
    19
    Rep Power
    0

    Default Re: Saving Binary Tree to file

    I have yes. Currently looking into it now. Each node has a parentID, int ID; char fromWhichBranch and char questionAnswer; attached to it. Not too sure how serialization works though. Does the binary tree need to have any specific properties?

  6. #6
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,526
    Blog Entries
    7
    Rep Power
    20

    Default Re: Saving Binary Tree to file

    If your Node class implements the (empty) Serializable interface and all of its instance members do, there's nothing more you have to do, i.e. make the serialization mechanism save the root of your tree and the entire tree will be saved (in binary form).

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  7. #7
    vuzuggu is offline Member
    Join Date
    Oct 2011
    Posts
    19
    Rep Power
    0

    Default Re: Saving Binary Tree to file

    I'm still having trouble implement the serialization of the tree. Would you have any working examples of the code I could look at?

    Im currently working on assigning each node a ID, Parent ID, BranchID to save to a file and then input from that file but serialization sounds easier if it would work.

  8. #8
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,526
    Blog Entries
    7
    Rep Power
    20

    Default Re: Saving Binary Tree to file

    All you have to do is this:

    Java Code:
    public class Node implements Serializable { ... }
    Wrap an ObjectOutputStream around a FileStream and save the root of your tree; all other Nodes in your tree will be saved too. Read the API documentation for the details.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  9. #9
    vuzuggu is offline Member
    Join Date
    Oct 2011
    Posts
    19
    Rep Power
    0

    Default Re: Saving Binary Tree to file

    I'm still lost. Thanks so much for your help though.

    Would you be able to do a massive favour and see if there is anything blatantly obvious in my code which prevents it from working?

    [Java] import java.io.FileOutputStream; import java.io.IOException; import java.io.Ob - Pastebin.com and [Java] import tcdIO.Terminal; public class AMVsetup { static String question; - Pastebin.com

    Thanks

  10. #10
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,526
    Blog Entries
    7
    Rep Power
    20

    Default Re: Saving Binary Tree to file

    In your code I saw this:

    Java Code:
    outputStream.writeObject(first.question);
    That only saves the question of the first Node (a String); you don't want that; do this instead:

    Java Code:
    outputStream.writeObject(first);
    Now that first Node and all the Nodes it references etc. are saved, i.e. the entire tree is saved.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  11. #11
    AndrewM16921 is offline Senior Member
    Join Date
    Jan 2009
    Location
    CA, USA
    Posts
    264
    Rep Power
    6

    Default Re: Saving Binary Tree to file

    I recently wrote a class to save configuration files for some projects I'm working on. It isn't a binary tree per se, but it can be easily modified to be. I don't know if it will help you much, but I will post it here so that you can have a look at it. I didn't implement serializable because I wanted the files to be human readable and editable. If this doesn't suit your needs, then serializable would be a better option. I'm no expert with serialization myself so I can't really help you there. :/

    Java Code:
    package org.nubcraft.util;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.HashMap;
    
    public class ConfigNode
    {
    	//Variables
    	public final static int INDENT =  4;
    	private String name, value;
    	private HashMap<String, ConfigNode> children;
    	
    	//Constructors
    	public ConfigNode(String name, String value)
    	{
    		this.name = name;
    		this.value = value;
    		children = new HashMap<String, ConfigNode>();
    	}
    	
    	public ConfigNode(String name)
    	{
    		this.name = name;
    		value = null;
    		children = new HashMap<String, ConfigNode>();
    	}
    	
    	private ConfigNode()
    	{
    		name = "Root";
    		value = null;
    		children = new HashMap<String, ConfigNode>();
    	}
    	
    	//get methods
    	public String getName()
    	{
    		return name;
    	}
    	
    	public boolean hasValue()
    	{
    		return value != null;
    	}
    	
    	public String get()
    	{
    		return value;
    	}
    	
    	public String getString()
    	{
    		return value;
    	}
    	
    	public Boolean getBoolean()
    	{
    		String val = value.toString();
    		if(val.equalsIgnoreCase("true"))
    			return true;
    		return false;
    	}
    	
    	public Integer getInteger()
    	{
    		try
    		{
    			int i = Integer.parseInt(value);
    			return i;
    		}
    		catch(NumberFormatException e)
    		{
    			return null;
    		}
    	}
    	
    	public Short getShort()
    	{
    		try
    		{
    			short s = Short.parseShort(value);
    			return s;
    		}
    		catch(NumberFormatException e)
    		{
    			return null;
    		}
    	}
    	
    	public Float getFloat()
    	{
    		try
    		{
    			float f = Float.parseFloat(value);
    			return f;
    		}
    		catch(NumberFormatException e)
    		{
    			return null;
    		}
    	}
    	
    	public Double getDouble()
    	{
    		try
    		{
    			double d = Double.parseDouble(value);
    			return d;
    		}
    		catch(NumberFormatException e)
    		{
    			return null;
    		}
    	}
    	
    	//is methods
    	public boolean isBoolean()
    	{
    		return getBoolean() != null;
    	}
    	
    	public boolean isInteger()
    	{
    		return getInteger() != null;
    	}
    	
    	public boolean isDouble()
    	{
    		return getDouble() != null;
    	}
    	
    	//Methods involving children
    	public boolean isLeaf()
    	{
    		return numChildren() == 0;
    	}
    	
    	public int numChildren()
    	{
    		return children.size();
    	}
    	
    	public boolean hasPath(String path)
    	{
    		String[] names = path.split("\\.");
    		ConfigNode current = this;
    		for(String name : names)
    		{
    			if(!current.hasChild(name))
    				return false;
    			current = current.getChild(name);
    		}
    		return true;
    	}
    	
    	public void addPath(String path)
    	{
    		String[] names = path.split("\\.");
    		ConfigNode current = this;
    		for(String name : names)
    		{
    			if(!current.hasChild(name))
    				current.addChild(name);
    			current = current.getChild(name);
    		}
    	}
    	
    	public boolean hasChild(String name)
    	{
    		return children.containsKey(name);
    	}
    	
    	public boolean hasChildByPath(String path, String name)
    	{
    		if(hasPath(path))
    		{
    			return getChildByPath(path).hasChild(name);
    		}
    		return false;
    	}
    	
    	public boolean hasChildren()
    	{
    		return numChildren() > 0;
    	}
    	
    	public boolean hasChildrenByPath(String path)
    	{
    		if(hasPath(path))
    		{
    			return getChildByPath(path).hasChildren();
    		}
    		return false;
    	}
    	
    	public ConfigNode getChild(String name)
    	{
    		return children.get(name);
    	}
    	
    	public ConfigNode[] getChildren()
    	{
    		return children.values().toArray(new ConfigNode[children.size()]);
    	}
    	
    	public ConfigNode getChildByPath(String path)
    	{
    		String[] names = path.split("\\.");
    		ConfigNode current = this;
    		for(String name : names)
    		{
    			if(!current.hasChild(name))
    				return null;
    			current = current.getChild(name);
    		}
    		return current;
    	}
    	
    	public ConfigNode getChildByPath(String path, String name)
    	{
    		String[] names = path.split("\\.");
    		ConfigNode current = this;
    		for(String cname : names)
    		{
    			if(!current.hasChild(cname))
    				return null;
    			current = current.getChild(cname);
    		}
    		if(current.hasChild(name))
    			return current.getChild(name);
    		return null;
    	}
    	
    	public ConfigNode addChild(ConfigNode node)
    	{
    		children.put(node.getName(), node);
    		return node;
    	}
    	
    	public ConfigNode addChild(String name)
    	{
    		ConfigNode child = new ConfigNode(name, null);
    		addChild(child);
    		return child;
    	}
    	
    	public ConfigNode addChild(String name, String value)
    	{
    		ConfigNode child = new ConfigNode(name, value);
    		addChild(child);
    		return child;
    	}
    	
    	public void addChildren(ConfigNode[] nodes)
    	{
    		for(ConfigNode node : nodes)
    			children.put(node.getName(), node);
    	}
    	
    	public void addChildren(String[] names)
    	{
    		for(String name : names)
    			children.put(name, new ConfigNode(name));
    	}
    	
    	public ConfigNode addChildByPath(String path, ConfigNode node)
    	{
    		addPath(path);
    		ConfigNode current = getChildByPath(path);
    		if(current != null)
    			current.addChild(node);
    		return node;
    	}
    	
    	public ConfigNode addChildByPath(String path, String name)
    	{
    		addPath(path);
    		ConfigNode current = getChildByPath(path);
    		if(current != null)
    			return current.addChild(name, null);
    		return null;
    	}
    	
    	public ConfigNode addChildByPath(String path, String name, String value)
    	{
    		addPath(path);
    		ConfigNode current = getChildByPath(path);
    		if(current != null)
    			return current.addChild(name, value);
    		return null;
    	}
    	
    	public ConfigNode removeChild(String name)
    	{
    		return children.remove(name);
    	}
    	
    	public void removeChildren()
    	{
    		children.clear();
    	}
    	
    	public void removeChildren(String[] names)
    	{
    		for(String name : names)
    			children.remove(name);
    	}
    	
    	public ConfigNode removeChildByPath(String path, String name)
    	{
    		ConfigNode current = getChildByPath(path);
    		if(current != null && current.hasChild(name))
    			return current.removeChild(name);
    		return null;
    	}
    	
    	//Other methods
    	public static ConfigNode createRoot()
    	{
    		return new ConfigNode();
    	}
    	
    	//File handling
    	public static ConfigNode load(String path, String filename) throws IOException
    	{
    		new File(path).mkdirs();
    		BufferedReader IN = new BufferedReader(new FileReader(path+filename));
    		String line = "";
    		HashMap<Integer, ConfigNode> parents = new HashMap<Integer, ConfigNode>();
    		ConfigNode root = createRoot(), current = null;
    		parents.put(-1, root);
    		while(true)
    		{
    			line = IN.readLine();
    			if(line == null)
    				break;
    			int indentation = 0;
    			for(int i = 0; i < line.length(); i++)
    			{
    				if(line.charAt(i) == ' ')
    					indentation++;
    				else
    					break;
    			}
    			indentation /= INDENT;
    			String[] lineComponents = line.trim().split(": ");
    comment:	{
    				if(lineComponents.length > 0)
    				{
    					if(lineComponents[0].startsWith("#") || lineComponents[0].equals(""))
    						break comment;
    					if(lineComponents.length == 1)
    					{
    						current = new ConfigNode(lineComponents[0], null);
    					}
    					else
    					{
    						current = new ConfigNode(lineComponents[0], lineComponents[1]);
    					}
    					parents.put(indentation, current);
    					parents.get(indentation-1).addChild(current);
    					current = null;
    				}
    			}
    		}
    		IN.close();
    		return root;
    	}
    	
    	public static void save(String path, String filename, ConfigNode config) throws IOException
    	{
    		new File(path).mkdirs();
    		BufferedWriter OUT = new BufferedWriter(new FileWriter(path+filename));
    		OUT.write(toStringRecursive(config));
    		OUT.close();
    	}
    	
    	//toString methods
    	
    	public String toString()
    	{
    		if(value == null)
    			return name;
    		else
    			return name + ": " + value;
    	}
    	
    	public String toString(int indentation)
    	{
    		indentation *= INDENT;
    		String str = "";
    		for(int i = 0; i < indentation; i++)
    		{
    			str += ' ';
    		}
    		return str+toString();
    	}
    	
    	public String toStringRecursive()
    	{
    		return toStringRecursive(this, -1);
    	}
    	
    	public String toStringRecursive(int indentation)
    	{
    		return toStringRecursive(this, indentation);
    	}
    	
    	public static String toStringRecursive(ConfigNode config)
    	{
    		return toStringRecursive(config, -1);
    	}
    	
    	public static String toStringRecursive(ConfigNode config, int indentation)
    	{
    		String str = "";
    		if(indentation >= 0)
    			str = config.toString(indentation) + '\n';
    		indentation++;
    		for(ConfigNode child : config.getChildren())
    		{
    			str += toStringRecursive(child, indentation);
    		}
    		indentation--;
    		return str;
    	}
    }

  12. #12
    vuzuggu is offline Member
    Join Date
    Oct 2011
    Posts
    19
    Rep Power
    0

    Default Re: Saving Binary Tree to file

    AndrewM Thanks for the code. I think I am nearly there will serialization so Im going to keep trying it.

    JosAH I owe you big time. Thanks so much for your help. As far as I know it is now serialization the tree to file. I opened the file it creates and its all random characters with the odd word I recognise so I presume thats a good sign! My code new code is [Java] import java.io.FileInputStream; import java.io.FileOutputStream; import java.i - Pastebin.com and the set up file remains unchanged.

    I am not sure how to deserialize the tree and then use it again in the program. At the moment, I call the deserialize code and then initiate the node first with the standard values which seems to overwrite the tree imported from the file. But if I remove the coding from line 61 -> 66 I just get null values. I'm not really sure where or how to proceed?

  13. #13
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,526
    Blog Entries
    7
    Rep Power
    20

    Default Re: Saving Binary Tree to file

    Quote Originally Posted by vuzuggu View Post
    I am not sure how to deserialize the tree and then use it again in the program. At the moment, I call the deserialize code and then initiate the node first with the standard values which seems to overwrite the tree imported from the file. But if I remove the coding from line 61 -> 66 I just get null values. I'm not really sure where or how to proceed?
    When you use an ObjectInputStream wrapped around a FileInputStream and make it read, it reads a Node object and everything attached to it (i.e. the entire tree); it is your first Node you wrote to the stream before. Do with it what you want.

    kind regards,

    Jods
    cenosillicaphobia: the fear for an empty beer glass

  14. #14
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,421
    Rep Power
    25

    Default Re: Saving Binary Tree to file

    Can you post your current version of the program here?

  15. #15
    vuzuggu is offline Member
    Join Date
    Oct 2011
    Posts
    19
    Rep Power
    0

    Default Re: Saving Binary Tree to file

    Norm,

    The current program is on [Java] import java.io.FileInputStream; import java.io.FileOutputStream; import java.i - Pastebin.com and [Java] import java.io.FileInputStream; import java.io.FileOutputStream; import java.i - Pastebin.com

    I still am unsure how to deserialize the program and work from the binary tree. Any help would be appreciated. Once I get it working I will post the code on here for otheres to use in the future.

  16. #16
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,421
    Rep Power
    25

    Default Re: Saving Binary Tree to file

    It's much easier to talk about code that can be seen in the thread.
    Java Code:
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
     
    public class Assignment1 extends AMVsetup  implements Serializable {
            private static final long serialVersionUID = 1L;
     
    static class Node implements Serializable       {
            private static final long serialVersionUID = 6265978352799255699L;
                    public String question;    
                    public Node True;    
                    public String name;  
                    public Node False;
                    public int parentID;
                    public int ID;
                    public char fromWhichBranch;   
                    public char questionAnswer;
                   
     
     
    public void branch()    {        
                    if(question != null)            {                
                            input = terminal.readString(question + "\n");  
                    if (input.contains("true"))                
                            True.branch();                
                    else                
                            False.branch();              
                    }        
                    else if(question == null)       {            
                    input = terminal.readString("Is it a/an " + name + "?\n");                    
                    if(input.contains("true"))              
                    {  terminal.println("I win!"); }            
                    else  {                                            
                         terminal.println("I give up.\n");                
                         newName = terminal.readString("What were you thinking of?\n");                
                                           
                         newQuestion = terminal.readString("What is a question that you " + "would answer no to " + newName + ", but " + "yes to " + name + "?\n");                              
                         True = new Node();                
                         True.name = name;    
                         False = new Node();                
                         False.name = newName;
                         name = null;              
                         question = newQuestion;                
                         terminal.println(newName + " has been added to the game.");            
                     }                    
                    }          
                    }      
    }
           
     
    public static void main(String[] args) throws Exception {
           
            terminal.println("Welcome to my AMV Game\n");
           
            readFile();
             
             Node first = new Node();
             first.question = "Is it an animal?";
             first.True = new Node();
             first.True.name = "Elephant";
             first.False = new Node();
             first.False.question = "Is it a Vegetable?";
             first.False.True = new Node();
             first.False.True.name = "Carrot";
             first.False.False = new Node();
             first.False.False.name = "Coal";
                                    do  {
                                                    first.branch();
                                                    end = terminal.readString("Quit or play again?");
                                            }  while(end.equals("again"));
                                                   
                   
                            terminal.println("The game has ended.");
                            writePersons(first);
                            System.out.println(first);
             
                           
            }
     
    public static void writePersons(Node first) throws Exception {
           
           ObjectOutputStream outputStream = null;
           try {
               
               outputStream = new ObjectOutputStream(new FileOutputStream("C:\\Users\\Daniel\\My Documents\\College\\CS1011\\testfiles\\index.txt"));      
               outputStream.writeObject(first);
           
           } finally {
               //Close the ObjectOutputStream
                               outputStream.flush();
                       outputStream.close();
                   }
               
           }
     
     
    static public void readFile(String ... args) {
                    Node first = null;
                    try {
                   
                            FileInputStream flinpstr = new FileInputStream("C:\\Users\\Daniel\\My Documents\\College\\CS1011\\testfiles\\index.txt");
                            ObjectInputStream objinstr= new ObjectInputStream(flinpstr);
                            try {  
                                   
                                    first = (Node) objinstr.readObject();
                            } finally {
                                   
                                    try {
                                            objinstr.close();
                                    } finally {
                                            flinpstr.close();
                                    }
                            }
                    } catch(IOException ioe) {
                            ioe.printStackTrace();
                    } catch(ClassNotFoundException cnfe) {
                            cnfe.printStackTrace();
                    }
                    if(first != null) {
                            System.out.println(first + " has been deserialize");
                    }
            }
    }

  17. #17
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,421
    Rep Power
    25

    Default Re: Saving Binary Tree to file

    Look at line 103. What happens to that variable when the method exits?

  18. #18
    vuzuggu is offline Member
    Join Date
    Oct 2011
    Posts
    19
    Rep Power
    0

    Default Re: Saving Binary Tree to file

    Thanks to everyone for their help. I still cant get it though. I am not really to sure how to deserialize the tree and would really appreciate someone explaining it as I am as confused as a cow on astroturf!

  19. #19
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,421
    Rep Power
    25

    Default Re: Saving Binary Tree to file

    how to deserialize the tree
    Has the tree been serialized?
    Print out the tree's contents immediately before you write it out.
    When you read it in, print out its contents immediately to see if you have read what you wrote.

Similar Threads

  1. Replies: 2
    Last Post: 04-20-2011, 05:39 PM
  2. Replies: 0
    Last Post: 04-04-2010, 07:40 AM
  3. Creating a Tree and then saving the Tree
    By jackmatt2 in forum New To Java
    Replies: 0
    Last Post: 08-22-2009, 12:51 PM
  4. Help loading a Binary Tree from file
    By ExplosiveWeasel in forum Java 2D
    Replies: 16
    Last Post: 12-17-2008, 01:34 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •