我正在尝试将向量转换为序列化文件。该向量由我创建的一个类组成。下面是课堂。
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的向量。我一整天都在试验这个,似乎无法正确或在互联网上找到任何有用的东西。