1

Okay, so my issue is that i have alot of programs that i am using in java that use the exact same array of objects but i dont want to keep recreating this array every time that i write a new program. Is there a way to save an array of objects for use in other java programs. if so how?

user1593821
  • 13
  • 1
  • 3

4 Answers4

3

If you are a beginner you should serialize the array of objects into a file. The convention is to name your serialized file name-of-file.ser

try
      {
     FileOutputStream fileOut = new FileOutputStream("card.ser");//creates a card serial file in output stream
     ObjectOutputStream out = new ObjectOutputStream(fileOut);//routs an object into the output stream.
     out.writeObject(array);// we designate our array of cards to be routed
     out.close();// closes the data paths
     fileOut.close();// closes the data paths
  }catch(IOException i)//exception stuff
  {
      i.printStackTrace();
}

to deserialze it use this:

try// If this doesnt work throw an exception
         {
            FileInputStream fileIn = new FileInputStream(name+".ser");// Read serial file.
            ObjectInputStream in = new ObjectInputStream(fileIn);// input the read file.
            object = (Object) in.readObject();// allocate it to the object file already instanciated.
            in.close();//closes the input stream.
            fileIn.close();//closes the file data stream.
        }catch(IOException i)//exception stuff
        {
            i.printStackTrace();
            return;
        }catch(ClassNotFoundException c)//more exception stuff
        {
            System.out.println("Error");
            c.printStackTrace();
            return;
        }
Dylan
  • 189
  • 12
1

To serialize an object, create an ObjectOutputStream and call writeObject.

// Write to disk with FileOutputStream
FileOutputStream f_out = new 
    FileOutputStream("myobject.data");

// Write object with ObjectOutputStream
ObjectOutputStream obj_out = new
    ObjectOutputStream (f_out);

// Write object out to disk
obj_out.writeObject ( myArray );

Reference

Antimony
  • 37,781
  • 10
  • 100
  • 107
0

You can serialize many kinds of objects. Yes, an array is a object too (@see Array class). If you don't wan't the limitations of Arrays, you could use one of the Container classes (eg LinkedList) too. The serialization works the same way.

drjd
  • 399
  • 1
  • 2
-1

Write a class that manages this array. Put this class, along with classes it depends on, in its own JAR. Re-use JAR across multiple programs.

If you use Eclipse, you can do that by creating a new Java project (let's call it project OM - from Object Model) and putting the Foo and FooManager classes there. Then in each project you want to reuse the objects, in the Build Properties of the project add the OM project to the class path and to the exports tab. That's it.

Tassos Bassoukos
  • 16,017
  • 2
  • 36
  • 40