2012-05-29 6 views
-1

개체를 문서에 넣으려고합니다. 그 다음에 그들은 읽을 수 있습니다. 문제는 내가 가지고있는 파일을 읽을 수 있다는 것입니다. 폴더에 파일이있는 경우 폴더를 찾은 것입니다 ...레코더/플레이어 개체를 사용하는 방법

나는 objets와 같이 작업하고 있습니다 :

public class Person { 
    public int Id; 
    public String Name; 
    public boolean Show; 

    public Persona(
      int identificator, 
      String newName, 
      boolean ShoworNot 
      ){ 
     this.Id = identificator; 
     this.Name = newName; 
     this.Show = ShoworNot; 
    } 

Thanks 
my code: 

public void WriteFile 
try { 
      FileOutputStream file = new FileOutputStream("try.dat"); 
      ObjectOutputStream exit = new ObjectOutputStream(file); 
      Iterator ite2 = people.iterator(); 
      while(ite2.hasNext()){ 
      Person person2 = (Person)ite2.next(); 
      exit.writeObject(person2); 
      exit.close(); 
     } 
      System.out.println("It's works"); 

     } 
     catch (IOException e){ 
     System.out.println("Problems with the file."); 
     } 
} 
    } 
    } 
    } 
    public void ReadFile(){ 
     try { 
FileInputStream file2 = new FileInputStream("try.dat"); 
ObjectInputStream entry = new ObjectInputStream(file2); 
entry.readObject(); 
String data = (String)entry.readObject(); 
     entry.close(); 
System.out.println(data); 
} 

catch (FileNotFoundException e) { 
System.out.println("It can't open the file document"); 
} 
catch (IOException e) { 
System.out.println("Problems with the file"); 
} 
catch (Exception e) { 
System.out.println("Error reading the file"); 
} 
} 

답변

0

ObjectOutputStream을 사용하려면 개체에 Serializable 인터페이스를 구현해야합니다. 그것을 무시하고하려고,

entry.readObject(); 
String data = (String)entry.readObject(); 

당신이 1 개체를 읽고 : 그냥 문제가 당신이 실수를 e.printStackTrace()

쓰기 catch{} 각 블록에 뭐가 있는지 public class Person implements Serializable { 또한

public class Person { 변경 두 번째 객체를 읽지 만 이미 읽었으므로 파일의 끝에 있고 EndOfFileException (EOF)을 얻습니다. 첫 번째 줄을 제거하십시오. 두 번째 문제는 객체의 유형이 유효하지 않다는 것입니다. 당신이 파일과 닫고 스트림하기 전에 모든 데이터를 전송 후 나는 내 대답을 편집 .flush()

exit.writeObject(person2); 
exit.flush(); 
exit.close(); 
+0

를 호출해야합니다 또한

Person data = (Person) entry.readObject(); 

: 당신이하지 StringPerson을 읽을 수 있어야합니다, 그래서 당신은 객체 Person를 작성 – alaster

관련 문제