2013-02-25 70 views
0

我正在尝试向量到一个序列化的文件。该向量由我创建的类组成。下面是这堂课。写入并读取矢量到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的向量中。我一直在尝试这一整天,似乎无法得到任何正确的东西,或者在互联网上找到任何有用的东西。

+1

哪里是代码部分,你在哪里写你的矢量文件? – 2013-02-25 13:00:16

+0

我认为这就是他想做的事情......把它写到一个文件中,他称之为“序列化文件” – 2013-02-25 13:07:22

+0

你对序列化文件有什么意思? – 2013-02-25 13:08:53

回答

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] 
+0

我尝试了读取文件的代码,只是从文件中读取的代码,我得到了一个 “线程中的异常”main“java.lang.ClassNotFoundException” ,然后是一个完整的“at java”列表。 something.something”。最后一行告诉我它与该行有关:“final Vector productsFromFile =(Vector )in。readObject();“ – user2107258 2013-02-27 13:43:04

+0

很高兴知道哪个类无法找到,通常这个信息直接出现在”java.lang.ClassNotFoundException“输出之后,我认为它是'Product'类,那么你应该检查你的'Product'类在同一个包中,或者您必须在'Main'类的顶部插入'import'语句。 – vanje 2013-02-27 15:18:01

+0

找不到'Product'类,但'Product'类位于同一个包中。 好的,我发现了这个问题,我为两个独立的项目创建了一个新的类'Product',一个用于编写可序列化的文件,另一个用于读取它,然后读取可序列化的文件,但由于它没有正确的'产品'类,它抛出了异常。 感谢您的帮助! – user2107258 2013-02-28 01:03:41

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

+0

非常感谢!我还有一个问题,我不知道如何将文件读入产品的矢量。如何一次读取文件中的一个对象? – user2107258 2013-02-25 14:22:47

0

我认为你忘了将该向量添加到类中。在您的代码中,您将temp分配给新产品,然后将值添加到向量中。向量充满了新的值,但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; 
    } 
}