2017-07-17 87 views
-1

我在JAVA中讀取一個文件並根據用戶規範將數據轉換爲鏈接列表或樹,但是如何將數據保存到文件中(作爲數據結構) ,所以下次我讀取數據時,我不必花費額外的精力來解析文件。使數據結構持久

+0

您可以使用序列化的文件中寫入的樹,然後反序列化它,當你想讀它。 – Slimu

回答

0

你可以像這樣的數據保存到文件,它不是一個鏈表,但它有助於理解

//save persons 
public void savePersons(){ 
try{ 
    PersonsInfo p; 
    String line; 
    FileWriter fw= new FileWriter("input.txt"); 
    PrintWriter pw= new PrintWriter(fw); 
    for (int i=0 ; i<persons.size();i++){ 
     p =(PersonsInfo)persons.get(i); 
     line = p.getName() +","+ p.getAddress() +","+ p.getPhoneNum(); 
     pw.println(line); 
    } 
    pw.flush(); 
    pw.close(); 
    fw.close(); 
} catch (IOException ioEx){ 
System.out.println(ioEx); 
} 

,你可以檢索這樣的數據,你不需要在每一次

public class AddressBook{ 
ArrayList<PersonsInfo> persons; 
public AddressBook(){ 
    persons = new ArrayList <PersonsInfo>(); 
    loadPersons(); 
} 
//Load Person 
public void loadPersons(){ 
String tokens[]=null; 
String name,address,phoneNum; 
try{ 
    FileReader fr= new FileReader("input.txt"); 
    BufferedReader br= new BufferedReader(fr); 
    String line=br.readLine(); 
    while (line !=null) 
    { 
     tokens = line.split(","); 
     name=tokens[0]; 
     address=tokens[1]; 
     phoneNum=tokens[2]; 
     PersonsInfo p = new PersonsInfo(name,address,phoneNum); 
     persons.add(p); 
     line = br.readLine(); 
    } 

br.close(); 
fr.close(); 

}catch (IOException ioEx) { 
     System.out.println(ioEx); 
} 
} 
0

這取決於你想如何存儲數據解析文件:

  • 如果您不想將數據存儲在人類可讀的形式,那麼你可以用Serialization(例如here)繼續。 Java將分別在寫/讀操作期間負責存儲/構造對象/結構。
  • 如果你想以人類可讀的形式存儲數據,那麼你可以將數據轉換成比如json並以String格式存儲它。您可以使用傑克遜的ObjectMapper類,例如:

    ObjectMapper mapper = new ObjectMapper(); YourClass object = new YourClass(); FileOutputStream outputStream = new FileOutputStream("path_to_file"); outputStream.write(mapper.writeValueAsBytes(object));

    //Read YourClass persisted = mapper.readValue("path_to_file", YourClass.class);

    Here's的例子,這裏是Jackson's文檔。

0

您可以使用serialization這是一個Java的功能,因此非常容易使用:

節省:

ObjectOutputStream oos = null; 
try { 
     LinkedList<String> list = new LinkedList<>(); 
     list.add("toto"); list.add("tata"); 

     oos = new ObjectOutputStream(new FileOutputStream("C:\\Users\\..\\Doc\\list.ser")); 
     oos.writeObject(list); 
} catch ... { 
}finally (oos.close) ...{ 
} 

當然,如果這不是你改變LinkedList,無論你想要


負載:

ObjectInputStream ois = null; 

try { 
    ois = new ObjectInputStream(new FileInputStream("C:\\Users\\..\\Doc\\list.ser")); 

    final LinkedList<String> list = (LinkedList<String>) ois.readObject(); 
    System.out.println(list.toString()); //[toto,tata] 
} catch ... { 
}finally (ois.close) ...{ 
} 

在編寫您使用writeObject,並在閱讀您使用readObject + casting向好的類型(這樣的順序是非常重要的,如果你寫了一個名單,然後字符串,然後其他的,你可以閱讀列表此後字符串,然後其他)

Serialization Details