Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures - Retired Organizing Data Serialization

Matthew Francis
Matthew Francis
6,967 Points

What does writeObject() and readObject() does?

I tried reading the documentation/re-listen to what Craig' said, but can't seem to fully comprehend what the they do.

This is my undertanding, not sure if it is right. Code:

public class Treets{
  public static void save(Treet[] treets){
    try(
        FileOutputStream fos = new FileOutputStream("trees.ser");//sequence of bytes --> file
        ObjectOutputStream oos =  new ObjectOutputStream(fos);//object --> sequence of bytes
    )
    {
      oos.writeObject(treets);//means: what object to convert to sequence of bytes?

    public static Treet[] load(){
      Treet[] treets = new Treet[0];
      try(
        FileInputStream fis = new FileInputStream("treets.ser");//sequence of bytes <-- file
        ObjectInputStream ois = new ObjectInputStream(fis);) //sequence of bytes --> object.
      {
        treets = (Treet[]) ois.readObject(); //means: what file to convert to an object
      return treets;
    }
  }
}

1 Answer

Hello, Matthew, I have struggled on with the same problem. And I think I have found an answer:

public class Treets{

  public static void save(Treet[] treets){

    try(
        FileOutputStream fos = new FileOutputStream("trees.ser");// RECEIVE sequence of bytes --> file
        ObjectOutputStream oos =  new ObjectOutputStream(fos);//CREATE AN object --> sequence of bytes( Like  a box 
for our future date) 
    )

    }
      oos.writeObject(treets);//means: Treets - is our date and we put it in our box. (We write specific information in our object)




public static Treet[] load(){
      Treet[] treets = new Treet[0];
      try(
        FileInputStream fis = new FileInputStream("treets.ser");//sequence of bytes <-- file
        ObjectInputStream ois = new ObjectInputStream(fis);) //sequence of bytes --> object.
      {
        treets = (Treet[]) ois.readObject(); //We again receive bytes from array of treets (It is a process of reconstruction of our data)
      return treets;
    }
}
}

I hope it will be helpful :)