1

我正在尝试将向量转换为序列化文件。该向量由我创建的一个类组成。下面是课堂。

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;
    }
}

我创建了一个向量:

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");

                    }
                }
            }
         }

所以我有一个产品向量。我需要知道的是如何将它写入序列化文件file.ser,然后如何从该文件读回Product的向量。我一整天都在试验这个,似乎无法正确或在互联网上找到任何有用的东西。

4

4 回答 4

2

我添加了一个toString()方法 do 类Product来获得正确的调试输出:

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

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

您可以将整个向量实例放到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);

  }

}

输出是:

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]
于 2013-02-25T14:26:07.480 回答
2

尝试以下类似的方法来编写一个可序列化的对象:

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.");
}

要阅读它,请执行相反的操作,将结果放入对象中,如下所示:

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

哪里inputObjectInputStream

于 2013-02-25T13:13:26.620 回答
0

我认为您忘记将向量添加到类中。在您的代码中,您将 temp 分配给新产品,然后将值添加到向量中。Vector 填充了新值,但 Vector 不是 Product 类的一部分。因此,数据仍然在 Vector 中,但永远不会通过可序列化的方式保存。(如果这是您尝试完成的)这是一个小示例(用 Java 处理编写):

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;
  }
}
于 2013-02-25T14:20:17.560 回答
0

我认为您可以使用此示例来写入和读取文件:

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

您可以在 google 中搜索:“java 文件阅读器示例”

问候

于 2013-02-25T13:11:36.357 回答