我正在嘗試向量到一個序列化的文件。該向量由我創建的類組成。下面是這堂課。寫入並讀取矢量到Java中的序列化文件?
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的向量中。我一直在嘗試這一整天,似乎無法得到任何正確的東西,或者在互聯網上找到任何有用的東西。
哪裏是代碼部分,你在哪裏寫你的矢量文件? – 2013-02-25 13:00:16
我認爲這就是他想做的事情......把它寫到一個文件中,他稱之爲「序列化文件」 – 2013-02-25 13:07:22
你對序列化文件有什麼意思? – 2013-02-25 13:08:53