1 2 Previous Next 15 Replies Latest reply: Dec 14, 2007 10:17 AM by 807601 RSS

    Writing objects to a file

    807601
      So .. I'd like to write a whole object to a file, but I can't seem to find the correct information on how to do it. I wrote out a SSCE (or whatever the acronym is) to post here. I have these two objects:
      public class Hero {
           private int level;
           private int gold;
           private String characterName;
           private String playerName;
           private ArrayList<Equipment> gear;
           
           public Hero(String n) { playerName = n; }
           
           public void setLevel(int l) { level = l; }
           public void setgold(int g) { gold = g; }
           public void setCharName(String n) { characterName = n; }
           public void addGear(Equipment e) {
                if (!gear.contains(e))
                     gear.add(e);
           }
           public void removeGear(Equipment e) {
                gear.remove(e);
           }
           
           public int getLevel() { return level; }
           public int getGold() { return gold; }
           public String getCharName() { return characterName; }
           public String getPlayerName() { return playerName; }
           public ArrayList<Equipment> getGear() { return gear; }
      }
      public class Equipment {
           private String name;
           
           public Equipment(String n) { name = n; }
           public String getName() { return name; }
      }
      And then I have this object to (hopefully) save the information:
      public class RecordKeeper {
           private FileWriter fw;
           private BufferedWriter bw;
           
           public void write(String file, Hero hero) {
                try {
                     fw = new FileWriter(file);
                     bw = new BufferedWriter(fw);
                     // write the hero class to a file here
                     bw.close();
                } catch (IOException e) {
                     e.printStackTrace();
                }
           }
      }
      Is the only way to do this to have a method in the Hero class convert all of it's information to a String? Or am I just taking the complete wrong approach for this?

      Any input is appreciated.
        • 1. Re: Writing objects to a file
          807601
          http://www.google.com/search?q=java+serialize+object+file
          • 2. Re: Writing objects to a file
            807601
            If you don't mind creating a binary file instead of a human-readable text file, the easiest approach is to use Serialization:

            http://java.sun.com/docs/books/tutorial/essential/io/objectstreams.html
            • 3. Re: Writing objects to a file
              807601
              1. You should be using an OutputStream, not a Writer (streams are byte oriented, writers are character oriented).
              2. All classes that will end up serialized need to implement java.io.Serializable.
              3. The class java.io.ObjectOutputStream can write objects to a stream.
              • 4. Re: Writing objects to a file
                807601
                Hey Lazlo (and others). Been a while. ;)

                I want a binary file, actually, instead of a human readable file..

                I looked at OutputStreamWriter also, but it appeared to have the same methods as FileWriter does.. Maybe I missed something, though.

                I'm not 100% familiar with the serializable interface. I'll go read up on that and possibly come back with more Q's.

                edit: Sorry - missed that you said ObjectOutputStream. I'll go check that out, also.

                Edited by: JJCoolB on Dec 14, 2007 8:20 AM
                • 5. Re: Writing objects to a file
                  807601
                  For the purpose of writing objects to binary files ... Strings do NOT count as a primitive data type, yes?
                  • 6. Re: Writing objects to a file
                    807601
                    JJCoolB wrote:
                    For the purpose of writing objects to binary files ... Strings do NOT count as a primitive data type, yes?
                    Correct, but they implement Serializable, as do many of the basic Java classes.
                    • 7. Re: Writing objects to a file
                      807601
                      If you are not wedded to non-text files, check out XMLEncoder/XMLDecoder in package java.beans.

                      Demo:
                      public class Equipment {
                          private String name;
                      
                          public Equipment() {}
                      
                          public Equipment(String name) {
                              setName(name);
                          }
                      
                          public String getName() {
                              return name;
                          }
                      
                          public void setName(String name) {
                              this.name = name;
                          }
                      
                          public String toString() {
                              return getName();
                          }
                      }
                      import java.util.*;
                      
                      public class Hero {
                          private int level;
                          private String characterName;
                          private List<Equipment> gear;
                      
                          public void setLevel(int level) {
                              this.level = level;
                          }
                      
                          public void setCharacterName(String characterName) {
                              this.characterName = characterName;
                          }
                      
                          public void setGear(List<Equipment> gear) {
                              this.gear = gear;
                          }
                      
                          public int getLevel() {
                              return level;
                          }
                      
                          public String getCharacterName() {
                              return characterName;
                          }
                      
                          public List<Equipment> getGear() {
                              return gear;
                          }
                      
                          public String toString() {
                              return getCharacterName() + " " + getLevel() + " " + getGear();
                          }
                      }
                      import java.beans.*;
                      import java.io.*;
                      import java.util.*;
                      
                      public class Demo {
                          public static void main(String[] args) throws IOException {
                              Hero h = new Hero();
                              h.setCharacterName("Lord Asriel");
                              h.setLevel(101);
                              List<Equipment> stuff = new ArrayList<Equipment>();
                              stuff.add(new Equipment("Dust"));
                              stuff.add(new Equipment("Alethiometer"));
                              h.setGear(stuff);
                              System.out.println(h);
                      
                              File file = new File("Test.xml");
                              XMLEncoder e = new XMLEncoder(
                                  new BufferedOutputStream(
                                      new FileOutputStream(file)));
                              e.writeObject(h);
                              e.close();
                      
                              XMLDecoder d = new XMLDecoder(
                                  new BufferedInputStream(
                                  new FileInputStream(file)));
                              Object result = d.readObject();
                              d.close();
                      
                              System.out.println(result);
                          }
                      }
                      Test.xml:
                      <?xml version="1.0" encoding="UTF-8"?> 
                      <java version="1.6.0" class="java.beans.XMLDecoder"> 
                       <object class="Hero"> 
                        <void property="characterName"> 
                         <string>Lord Asriel</string> 
                        </void> 
                        <void property="gear"> 
                         <object class="java.util.ArrayList"> 
                          <void method="add"> 
                           <object class="Equipment"> 
                            <void property="name"> 
                             <string>Dust</string> 
                            </void> 
                           </object> 
                          </void> 
                          <void method="add"> 
                           <object class="Equipment"> 
                            <void property="name"> 
                             <string>Alethiometer</string> 
                            </void> 
                           </object> 
                          </void> 
                         </object> 
                        </void> 
                        <void property="level"> 
                         <int>101</int> 
                        </void> 
                       </object> 
                      </java> 
                      • 8. Re: Writing objects to a file
                        807601
                        I'm not familiar with the new "helpful/correct" system yet. I'm not sure I like it, since it looks like you can only mark one reply as correct and 2 as helpful.

                        Anyway - one last question and then I'll mark this as answered.

                        I used the following to write a file.
                        public static void main(String[] args) {
                             Hero hero = new Hero("Joe");
                             hero.setCharName("Schmoe");
                             hero.setLevel(10);
                             hero.setgold(5000);
                             hero.addGear(new Equipment("Sword"));
                             hero.addGear(new Equipment("Shield"));
                             
                             RecordKeeper rk = new RecordKeeper();
                             rk.write(hero.getPlayerName(), hero);
                        }
                        and the binary file I got looks "correct".

                        My last question is about reading the file back. Because some objects are of varying lengths, the reading it back will automatically know how much to read? For instance, Strings and ArrayLists are of unknown lengths - does the writeObject/readObject method know the correct lengths when it reads it back?
                        • 9. Re: Writing objects to a file
                          807601
                          JJCoolB wrote:
                          My last question is about reading the file back. Because some objects are of varying lengths, the reading it back will automatically know how much to read? For instance, Strings and ArrayLists are of unknown lengths - does the writeObject/readObject method know the correct lengths when it reads it back?
                          Try it and see. Serializing/deserializing takes only a few lines of code to test.
                          • 10. Re: Writing objects to a file
                            807601
                            I'm not yet familiar with Serialization still, unfortunately. :( And I'm out of time for now. But I'll try to read up on it and understand it. (hopefully) I'll be back if not.

                            Thanks for the help, guys!
                            • 11. Re: Writing objects to a file
                              3004
                              JJCoolB wrote:
                              For the purpose of writing objects to binary files ... Strings do NOT count as a primitive data type, yes?
                              For any and all purposes Strings do not count as primitives. Because they're not.
                              • 12. Re: Writing objects to a file
                                807601
                                Yes, I know that... I was thinking from the standpoint that Strings, unlike most objects, are extremely easy to convert into a primitive object (an array of chars). My question was more-so directed about the fact that, when being written/read, a String's "unknown length" would have to be taken into account - thus I asked if it was treated like an object as opposed to an array of chars.
                                • 13. Re: Writing objects to a file
                                  807601
                                  Arrays are serializable, too (when their contents are).
                                  • 14. Re: Writing objects to a file
                                    807601
                                    JJCoolB wrote:
                                    Yes, I know that... I was thinking from the standpoint that Strings, unlike most objects, are extremely easy to convert into a primitive object (an array of chars). My question was more-so directed about the fact that, when being written/read, a String's "unknown length" would have to be taken into account - thus I asked if it was treated like an object as opposed to an array of chars.
                                    It is the serializer's job to record things like length. Arrays need their length stored, and since a String is an array of characters...
                                    1 2 Previous Next