2014-06-29 44 views
0

Java中的初學者,製作學生的程序有班級學生的管理,我想將學生的數據保存爲一個文本對象File .I嘗試使用Objectoutputstream ,但文件中的內容以某種尷尬的形式顯示。任何幫助都將得到極大的讚賞。將Class對象保存爲Java中的文本文件

+1

你想保存什麼?您是否想在稍後再次將其加載到程序中,或者該文件是否應該像XML一樣可讀? –

+0

人類可讀。 –

回答

3

你可以試試下面的示例代碼使用ObjectOutputStream在Java中,爲了把它寫在文件中:

import java.io.Serializable; 

public class Person implements Serializable { 

    private String firstName; 
    private String lastName; 
    private int age; 

    public Person() { 
    } 

    public String getFirstName() { 
     return firstName; 
    } 

    public void setFirstName(String firstName) { 
     this.firstName = firstName; 
    } 

    public String getLastName() { 
     return lastName; 
    } 

    public void setLastName(String lastName) { 
     this.lastName = lastName; 
    } 

    public int getAge() { 
     return age; 
    } 

    public void setAge(int age) { 
     this.age = age; 
    } 

    //Overriding toString to be able to print out the object in a readable way 
    //when it is later read from the file. 
    public String toString() { 

     StringBuffer buffer = new StringBuffer(); 
     buffer.append(firstName); 
     buffer.append("\n"); 
     buffer.append(lastName); 
     buffer.append("\n"); 
     buffer.append(age); 
     buffer.append("\n"); 

     return buffer.toString(); 
    } 


} 

這是一個用於創建Person類的實例,並將它們寫入到一個ObjectOuputStream的代碼:

import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.ObjectOutputStream; 

public class Main { 

    /** 
    * Example method for using the ObjectOutputStream class 
    */ 
    public void writePersons(String filename) { 

     ObjectOutputStream outputStream = null; 

     try { 

      //Construct the LineNumberReader object 
      outputStream = new ObjectOutputStream(new FileOutputStream(filename)); 

      Person person = new Person(); 
      person.setFirstName("James"); 
      person.setLastName("Ryan"); 
      person.setAge(19); 

      outputStream.writeObject(person); 

      person = new Person(); 

      person.setFirstName("Obi-wan"); 
      person.setLastName("Kenobi"); 
      person.setAge(30); 

      outputStream.writeObject(person); 


     } catch (FileNotFoundException ex) { 
      ex.printStackTrace(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } finally { 
      //Close the ObjectOutputStream 
      try { 
       if (outputStream != null) { 
        outputStream.flush(); 
        outputStream.close(); 
       } 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
     } 
    } 


    public static void main(String[] args) { 
     new Main().writePersons("myFile.txt"); 
    } 
} 

希望你有明確的想法和示例代碼。

謝謝。