1

I am trying a vector to a serialized file. The vector is made of a class I created. Below is the class.

public class Product implements java.io.Serializable{
    public String description;
    public String code;
    public double price;
    public String unit;

    public Product(String w, String x, double y, String z){ //Constructor for Product
        description = w;
        code = x;
        price = y;
        unit = z;
    }
}

I created a vector:

BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.ser"));
         Vector <Product> products=new Vector();//declare a vector of products
         for(int i=0;i<101;i++){//enter the values for the class
            System.out.print("Description: ");
            String w = in.readLine();
            char f = w.charAt(0);
            if(f=='#'){//Statement to break out of the loop when the user enters #                       
                System.out.println();
                break;
            }else{//Code to read input from user
                System.out.print("Code: ");
                String x = in.readLine().toUpperCase();
                boolean finished=false;
                while(!finished){
                    System.out.print("Price: ");
                    String a =in.readLine();   
                    try{//try catch statement 
                        double y= Double.parseDouble(a);
                        System.out.print("Unit: ");
                        String z = in.readLine();
                        Product temp = new Product(w, x, y, z);
                        products.insertElementAt(temp, i);//values are assigned to 
                        //the vector elements 
                        System.out.println();
                        finished=true;
                    }
                    catch(Exception e){
                        System.out.println("do not enter letters for the price");

                    }
                }
            }
         }

So I have a vector of Product. What I need to know is how to write it to into a serialized file, file.ser, then how to read from that file back into a vector of Product. I have been experimenting with this for a whole day and can't seem to get anything right or find anything useful on the internet.

4
  • 1
    Where is the code portion, where You are writing your vector to the file? Commented Feb 25, 2013 at 13:00
  • i think that is what he want to do... write it to a file, he called "serialized file" Commented Feb 25, 2013 at 13:07
  • what do you mean with serialized file? Commented Feb 25, 2013 at 13:08
  • 1
    Off-topic: don't use a Vector, use a List/ArrayList. Commented Feb 25, 2013 at 13:54

4 Answers 4

2

I added a toString() method do class Product to get proper debug output:

public class Product implements Serializable {
  // ....

  @Override
  public String toString() {
    return description + "/" + code + "/" + price + "/" + unit;
  }
}

You can put the whole vector instance to the ObjectOutputStream.

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;


public class Main {

  private static final String FILE_NAME = "file.ser";

  public static void main(String[] args) throws Exception {

    final Vector<Product> products = new Vector<Product>();

    products.add(new Product("1", "1", 1.0, "1"));
    products.add(new Product("2", "2", 2.0, "2"));
    products.add(new Product("3", "3", 3.0, "3"));
    products.add(new Product("4", "4", 4.0, "4"));

    System.out.println("Original products : " + products);

    final ObjectOutputStream out = new ObjectOutputStream(
        new BufferedOutputStream(new FileOutputStream(FILE_NAME)));

    try {
      out.writeObject(products);
    } finally {
      out.close();
    }

    final ObjectInputStream in = new ObjectInputStream(
        new BufferedInputStream(new FileInputStream(FILE_NAME)));

    final Vector<Product> productsFromFile = (Vector<Product>) in.readObject();

    System.out.println("Products from file: " + productsFromFile);

  }

}

And the output is:

Original products : [1/1/1.0/1, 2/2/2.0/2, 3/3/3.0/3, 4/4/4.0/4]
Products from file: [1/1/1.0/1, 2/2/2.0/2, 3/3/3.0/3, 4/4/4.0/4]
Sign up to request clarification or add additional context in comments.

3 Comments

I tried the code you gave for reading the file, just the one for reading from the file, I got a "Exception in thread "main" java.lang.ClassNotFoundException" and then a whole long list of "at java.something.something". The last line tells me it has to do with the line: "final Vector<Product> productsFromFile = (Vector<Product>) in.readObject();"
It would be nice to know which class could not be found. Usually this information comes directly after the "java.lang.ClassNotFoundException" output. I assume it's the Product class. Then you should check if your Product class in the same package or you have to insert an import statement on top of your Main class.
'Product' class could not be found, but the 'Product' class is in the same package. Ok I figured out the problem. I had made a new class 'Product' for the two separate projects I had. One to write the serializable file, the other to read it. I then read the serializable file, but since it did not have the correct 'Product' class, it threw the exception. Thanks for all the help!
2

Try something like the following to write a serialisable object:

Product product = new Product("Apples", "APP", 1.99, 200);
try{
  OutputStream file = new FileOutputStream( "output.ser" );
  OutputStream buffer = new BufferedOutputStream( file );
  ObjectOutput output = new ObjectOutputStream( buffer );
  try{
    output.writeObject(product);
  }
  finally{
    output.close();
  }
}  
catch(IOException ex){
  System.out.println("Output failed.");
}

To read it in you read do the opposite, putting result into an object as follows:

Product product = (Product)input.readObject();

where input is an ObjectInputStream.

1 Comment

Thank you very much! I've got a further problem that I don't know how to read the file into a vector of Product. How to I read the file one object at a time?
0

I think that you can use this example to write and read the file:

http://www.java-samples.com/showtutorial.php?tutorialid=392

you can search in google for: "java file reader example"

regards

Comments

0

I think that you forgot to add the vector to the class. In your code you assign temp to new Product, then you add the values to the vector. Vector is filled with new values, but Vector is not part of the class Product. Therefore, the data is still in Vector, but it's will never be saved via serializable. (if this is what you try to accomplish) Here is a small example (written in Java Processing):

import java.io.*;
GameChar Elf, Troll;
void setup() {
  Elf = new GameChar(50, new String[] { 
    "bow", "sword", "dust"
  }
  );
  Troll = new GameChar(200, new String[] { 
    "bare hands", "big axe"
  }
  );
  try {
    ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(sketchPath+"/data/game.txt"));
    os.writeObject(Elf); 
    os.writeObject(Troll); 
    os.close();
  }
  catch (Exception e) {
    println(e);
  }
  Elf = null;
  Troll = null;
  try {
    ObjectInputStream is = new ObjectInputStream(new FileInputStream(sketchPath+"/data/game.txt"));
    Elf = (GameChar) is.readObject();
    Troll = (GameChar) is.readObject();
    println("Elf has "+ Elf.getHealth()+" health, and fights with "+ Elf.getWeapons());
    println("Troll has "+ Troll.getHealth()+" health, and fights with "+ Troll.getWeapons());
  }
  catch (Exception e) {
    println(e);
  }
}
void draw() {
}
static class GameChar implements Serializable {
  int health;
  String[] weapons;
  GameChar(int h, String[] w) {
    health = h;
    weapons = w;
  }
  int getHealth() {
    return health;
  }
  String getWeapons() {
    String weaponList = "";
    for (String weapon : weapons) 
      weaponList += weapon + " ";
    return weaponList;
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.