我正在寻找如何在大学项目中使用ObjectInputStream。我发现了很多东西,但我不知道为什么我不能成功。最糟糕的是,我收到了越来越多的警告。
下面是我的三个类:
public class Contact implements Comparable<Contact>
{
private String nom;
private String prenom;
private int numTel;
private static int nbContacts;
private int numContact;
public Contact(String nom, int tel) //Constructeur nom et numero
{
System.out.println(this.numTel);
this.numTel = tel;
System.out.println(this.numTel);
this.nom = nom;
this.numContact=++nbContacts;
}
public Contact(String nom) //Constructeur Nom
{
this.nom = nom;
this.numContact=++nbContacts;
}
public Contact(String nom, String prenom, int tel) //Constructeur Nom, prenom, numero
{
this.numTel = tel;
this.nom = nom;
this.prenom = prenom;
this.numContact=++nbContacts;
}
public String getNom()
{
return this.nom;
}
public String getPrenom()
{
return this.prenom;
}
public int getTelephone()
{
return this.numTel;
}
public int getNumContact()
{
return this.numContact;
}
public void setNom(String nom)
{
this.nom = nom;
}
public void setNumTelephone(int num)
{
this.numTel = num;
}
public boolean equals(Contact contact)
{
if(!this.nom.equals(contact.getNom()))
{
return false;
}
if(this.numTel!=contact.getTelephone())
{
return false;
}
return true;
}
public int compareTo(Contact contact)
{
return (Integer.valueOf(this.nom) - Integer.valueOf(contact.getNom()));
}
public String toString()
{
String s = this.numContact + ") ";
s+= String.format ( "%-10s", "NOM : ") + this.nom;
if(this.prenom != null)
{
s+=" | " + String.format ( "%-10s", "PRENOM : " ) + this.prenom ;
}
if(this.numTel != 0)
{
s+= " : " + this.numTel;
}
s += "\n";
System.out.println(this.nom);
return s;
}
}下一步
import java.util.ArrayList;
import java.util.List;
import java.io.*;
import java.util.Collections;
public class Repertoire
{
private ArrayList<Contact>alContact;
public Repertoire()
{
alContact = new ArrayList<Contact>();
this.getData();
}
public String toString()
{
String s = "";
for ( int cpt = 0; cpt < alContact.size(); cpt++ )
{
s += alContact.get(cpt).toString() + "\n";
}
return s;
}
public void addContact(String nom, int tel) //Constructeur nom et numero
{
alContact.add(new Contact(nom, tel));
this.sauvegarder();
}
public void addContact(String nom) //Constructeur Nom
{
alContact.add(new Contact(nom));
this.sauvegarder();
}
public void addContact(String nom, String prenom, int tel) //Constructeur Nom, prenom, numero
{
alContact.add(new Contact(nom, prenom, tel));
this.sauvegarder();
}
// Permet d'enregistrer dans un fichier .dat les éléments du répertoire
private void sauvegarder()
{
try
{
ObjectOutputStream out = new ObjectOutputStream ( new FileOutputStream ("Rep.txt") );
out.writeObject ( alContact );
}
catch ( Exception e ) {}
}
public void getData()
{
FileInputStream fis = null;
ObjectInputStream in = null;
try
{
fis = new FileInputStream("~/Rep.txt");
in = new ObjectInputStream(fis);
alContact = (ArrayList) in.readObject();
in.close();
}
catch (IOException ex)
{
System.out.println("Bordel");
}
catch (ClassNotFoundException ex)
{
System.out.println("Gros Bordel");
}
}
// Permet de recuperer les donnée dans un fichier txt
private boolean charger()
{
try
{
System.out.println("Dedans");
ObjectInputStream in = new ObjectInputStream ( new FileInputStream ("Rep.txt"));
System.out.println("Dedans");
alContact = (ArrayList<Contact>) in.readObject();
System.out.println("Dedans");
}
catch ( Exception e )
{
System.out.println("Pas de fichier");
return false;
}
Collections.sort (alContact);
return true;
}}
只是一个测试
public class Test
{
public static void main(String[] args)
{
int tel;
Repertoire rep = new Repertoire();
/*System.out.println("Entrez le numero");
tel = Clavier.lire_int();
rep.addContact("José", tel);
*/System.out.println(rep);
}
}这个程序是一个电话索引。我尝试将索引保存到.txt/.dat文件中,但无法将其放入程序中。希望这是可以理解的。
发布于 2013-03-29 00:28:47
您的Contact类必须实现Serializable,以便可序列化以保存/读取InputObjectStream/OutputObjectStream。
来自ObjectInputStream文档:
类通过实现java.io.Serializable或java.io.Externalizable接口来控制它们的序列化方式
通过实现Serializable接口,对象序列化可以保存和恢复对象的整个状态,并且允许类在写入流和读取流之间不断发展。它自动遍历对象之间的引用,保存和恢复整个图形。
请注意,当您在程序中运行Repertoire#getData并且文件为空时,根本不会加载任何数据。因此,最好先在其中保存一些数据。您可以这样做来添加一些数据:
public void setStartData() {
Contact contact = new Contact("Luiggi", "Mendoza", 12345);
List<Contact> lstContact = new ArrayList<Contact>();
lstContact.add(contact);
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream("Rep.txt"));
out.writeObject(lstContact);
out.flush();
} catch (IOException e) {
System.out.println("Error while saving data.");
e.printStackTrace(System.out);
} finally {
if (out != null) {
out.close();
}
}
}其他建议:
将数据保存到文件中时,
static字段不会被序列化。Java将在文件中序列化,所以即使您将其视为文本文件,其内容也不会像人类可读的文本那样(至少您说的是Serializable language).
Serializable类中也应该是可序列化的。这意味着,如果你有一个对象实例在它里面,它的类必须实现 Serializable可以通过添加transient来从序列化中省略一个属性如果你保存数据,更改类定义并试图加载数据,你会得到一个错误。确保您的类在序列化/反序列化时具有相同的结构。看起来您是在为上一次错误运行此问题。发布于 2013-03-29 00:48:29
注意在Contact类中重写equals方法的方式。
其参数应为Object类型。应该是这样的
public boolean equals(Object obj)
{
if ( ! (obj instanceof Contact))
return false;
Contact contact = (Contact) obj;
if(!this.nom.equals(contact.getNom()))
{
return false;
}
if(this.numTel!=contact.getTelephone())
{
return false;
}
return true;
}另外,通过在定义Contact类的同时实现Serializable接口,使您的Contact类成为Serialzable。
您的sauvegarder方法应该如下所示:
private void sauvegarder()
{
ObjectOutputStream out = null;
try
{
out = new ObjectOutputStream ( new FileOutputStream ("Rep.txt") );
out.writeObject ( alContact );
}
catch ( Exception e ) {}
finally
{
if(out!=null)
{
try
{
out.close();//close the outputstream
}catch(Exception ex){}
}
}
}你的getData方法应该是这样的:
public void getData()
{
FileInputStream fis = null;
ObjectInputStream in = null;
try
{
fis = new FileInputStream("Rep.txt");//Why using ~/Rep.txt instead of Rep.txt?
in = new ObjectInputStream(fis);
alContact = (ArrayList<Contact>) in.readObject();
}
catch (IOException ex)
{
System.out.println("Bordel");
}
catch (ClassNotFoundException ex)
{
System.out.println("Gros Bordel");
}
finally
{
if(in != null)
{
try
{
in.close();
}catch(Exception ex){}
}
}
}你正在从一个不存在的文件中读取数据,因为到目前为止你还没有写任何东西,所以对于演示,你可以这样改变你的构造函数Repertoire:
public Repertoire()
{
alContact = new ArrayList<Contact>();
addContact("John",879999);
addContact("Micky",4333);
sauvegarder();
this.getData();
}并按如下方式更改您的Contact类声明:
public class Contact implements Comparable<Contact>,java.io.Serializablehttps://stackoverflow.com/questions/15687146
复制相似问题