我正在尝试一个序列化文件的向量。矢量由我创建的类组成。以下是课程。
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");
}
}
}
}
所以我有一个Product的矢量。我需要知道的是如何将其写入序列化文件file.ser,然后如何从该文件读回到Product的向量中。我一直在试验这一天,似乎无法做任何正确的事情或在互联网上找到任何有用的东西。
答案 0 :(得分: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();
其中input
是ObjectInputStream
。
答案 1 :(得分:0)
我认为您可以使用此示例来编写和读取文件:
http://www.java-samples.com/showtutorial.php?tutorialid=392
您可以在谷歌搜索:“java文件阅读器示例”
问候
答案 2 :(得分:0)
我认为您忘了将矢量添加到班级。在您的代码中,您将temp分配给新产品,然后将值添加到矢量。 Vector填充了新值,但Vector不属于Product类。因此,数据仍然在Vector中,但它永远不会通过可序列化保存。 (如果这是你想要完成的) 这是一个小例子(用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;
}
}
答案 3 :(得分:0)
我添加了toString()
方法做类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]