2015-08-09 44 views
0

我知道這個問題已經解決過,但是我根本無法找到答案,不管我多努力嘗試。 我想序列化和反序列化Java中的對象。我在反序列化中遇到問題。我沒有得到輸入的值,但是按照[email protected]的方法。爲什麼我得到這個而不是輸入的實際值?反序列化的Java問題

這裏是我的代碼

package prueba; 

import java.io.*; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Scanner; 

public class Prueba { 


public static void main(String[] args) throws FileNotFoundException,IOException, ClassNotFoundException { 
    File file = new File("f.txt"); 
    List <Estudiantes> lista = new ArrayList<>(); 
    boolean continuar = true; 
    while (continuar == true){ 
    Estudiantes es = new Estudiantes(); 
    System.out.println("Ingrese nombre"); 
    Scanner kb = new Scanner(System.in); 
    es.nombre = kb.nextLine(); 
    System.out.println("Ingrese Apellido"); 
    Scanner kb1 = new Scanner(System.in); 
    es.apellido = kb1.nextLine(); 
    System.out.println("Ingrese Número"); 
    Scanner kb2 = new Scanner(System.in); 
    es.numero = kb2.nextInt(); 
    lista.add(es); 

    FileOutputStream fo = new FileOutputStream(file); 
    ObjectOutputStream output = new ObjectOutputStream(fo); 

    for (Estudiantes est: lista){ 
     output.writeObject(est); 
    } 
    output.close(); 
    fo.close(); 


    FileInputStream fi = new FileInputStream(file); 
    ObjectInputStream input = new ObjectInputStream(fi); 
    ArrayList<Estudiantes> est2 = new ArrayList<Estudiantes>(); 
    try { 
     while (true){ 
      Estudiantes s = (Estudiantes)input.readObject(); 
      est2.add(s); 
     } 
    } 
    catch (EOFException ex){} 
    for (Estudiantes s :est2){ 
     System.out.println(s); 
    fi.close(); 
    input.close(); 
     } 

    System.out.println("0 para salir; 1 para continuar"); 
    Scanner kb3 = new Scanner(System.in); 
    int rev = kb3.nextInt(); 

    if (rev == 0){ 
     continuar = false; 
     System.out.println("Hasta Luego"); 
    } 
    } 
    } 
} 

這裏是我的拉普拉塔大學生類

package prueba; 

import java.io.Serializable; 

public class Estudiantes implements Serializable{ 
    String nombre, apellido; 
    int numero; 

} 

感謝

回答

-1

當您嘗試打印類讀回你以前寫你有對象時從Object類實現toString()方法是我的意思。 類改成這樣:

public class Estudiantes implements Serializable { 
    private static final long serialVersionUID = 123L; // has to be unique 
    String nombre, apellido; 
    int numero; 

    @Override 
    public String toString() { 
     System.out.println("first name: " + nombre); 
     System.out.println("last name: " + apellido); 
     System.out.println(numero); 
     return // a string you want to print 
    } 
} 
+0

是的;並沒有解決這個問題。 – EJP

+0

一切都應該現在工作,你的問題是你現在正在獲得你的對象的散列地址,因爲你重寫了toString方法,對象上的System.out.println調用將會調用你的類Estudiantes中的toString()方法。 –

+0

我得到這個錯誤在Netbeans中顯示「toString()在大學生不能重寫toString()在對象 返回類型void不兼容與字符串」in @Override – user3330990

0

我不明白中輸入的值,而是沿着[email protected]

這是線的東西你會得到什麼,當你明確或者對其類未覆蓋它的對象隱式調用toString()

這並非證據表明您有問題。

0

我認爲如果你得到像[email protected]這樣的值,你已經被反序列化了。你只需要正確地覆蓋toString()來獲得輸出。不知道這是否有幫助