1

さて、私の問題は、Javaで使用している、まったく同じオブジェクトの配列を使用するプログラムがたくさんあることですが、新しいプログラムを作成するたびにこの配列を再作成し続けたくありません。他のJavaプログラムで使用するためにオブジェクトの配列を保存する方法はありますか?もしそうなら、どのように?

4

4 に答える 4

3

初心者の場合は、オブジェクトの配列をファイルにシリアル化する必要があります。慣例では、シリアル化されたファイルにname-of-file.serという名前を付けます。

try
      {
     FileOutputStream fileOut = new FileOutputStream("card.ser");//creates a card serial file in output stream
     ObjectOutputStream out = new ObjectOutputStream(fileOut);//routs an object into the output stream.
     out.writeObject(array);// we designate our array of cards to be routed
     out.close();// closes the data paths
     fileOut.close();// closes the data paths
  }catch(IOException i)//exception stuff
  {
      i.printStackTrace();
}

デシリアライズするには、次を使用します。

try// If this doesnt work throw an exception
         {
            FileInputStream fileIn = new FileInputStream(name+".ser");// Read serial file.
            ObjectInputStream in = new ObjectInputStream(fileIn);// input the read file.
            object = (Object) in.readObject();// allocate it to the object file already instanciated.
            in.close();//closes the input stream.
            fileIn.close();//closes the file data stream.
        }catch(IOException i)//exception stuff
        {
            i.printStackTrace();
            return;
        }catch(ClassNotFoundException c)//more exception stuff
        {
            System.out.println("Error");
            c.printStackTrace();
            return;
        }
于 2012-08-12T18:53:07.967 に答える
1

オブジェクトをシリアル化するには、ObjectOutputStreamを作成し、writeObjectを呼び出します。

// Write to disk with FileOutputStream
FileOutputStream f_out = new 
    FileOutputStream("myobject.data");

// Write object with ObjectOutputStream
ObjectOutputStream obj_out = new
    ObjectOutputStream (f_out);

// Write object out to disk
obj_out.writeObject ( myArray );

参照

于 2012-08-12T18:52:21.877 に答える
0

多くの種類のオブジェクトをシリアル化できます。はい、配列もオブジェクトです(@see Arrayクラス)。配列の制限を望まない場合は、Containerクラスの1つ(LinkedListなど)を使用することもできます。シリアル化は同じように機能します。

于 2012-08-12T18:59:17.577 に答える
-1

この配列を管理するクラスを作成します。このクラスを、依存するクラスとともに、独自のJARに配置します。複数のプログラムでJARを再利用します。

Eclipseを使用している場合は、新しいJavaプロジェクト(オブジェクトモデルからプロジェクトOMと呼びましょう)を作成し、そこにFooクラスとFooManagerクラスを配置することでそれを行うことができます。次に、オブジェクトを再利用する各プロジェクトで、プロジェクトのビルドプロパティで、OMプロジェクトをクラスパスと[エクスポート]タブに追加します。それでおしまい。

于 2012-08-12T19:03:00.217 に答える