2013-02-25 74 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; 
    } 
}