1

シリアル化されたファイルへのベクターを試しています。ベクトルは、私が作成したクラスで構成されています。以下はクラスです。

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のベクターに読み取る方法です。私はこれを一日中実験してきましたが、インターネット上で何かを正しく理解したり、何か有用なものを見つけたりすることができないようです。

4

4 に答える 4

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

于 2013-02-25T13:13:26.620 に答える
2

適切なデバッグ出力を取得するために、toString()メソッドdoクラスを追加しました。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]
于 2013-02-25T14:26:07.480 に答える
0

ベクトルをクラスに追加するのを忘れたと思います。コードで、tempを新しいProductに割り当ててから、値をベクトルに追加します。Vectorは新しい値で埋められますが、VectorはProductクラスの一部ではありません。したがって、データはまだVectorにありますが、シリアライズ可能で保存されることはありません。(これがあなたが達成しようとしていることである場合)これは小さな例です(JavaProcessingで書かれています):

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;
  }
}
于 2013-02-25T14:20:17.560 に答える
0

この例を使用して、ファイルの書き込みと読み取りを行うことができると思います。

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

あなたはグーグルで検索することができます:「Javaファイルリーダーの例」

よろしく

于 2013-02-25T13:11:36.357 に答える