繁体   English   中英

用Java编写和读取Vector到序列化文件?

[英]Write and Read a Vector to a serialized file in 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的向量中。 我一直在试验这一天,似乎无法做任何正确的事情或在互联网上找到任何有用的东西。

尝试类似以下内容来编写可序列化对象:

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

我添加了一个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]

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

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

你可以在谷歌搜索:“java文件阅读器示例”

问候

我想你忘了把矢量添加到课堂上。 在您的代码中,您将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;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM