2015-12-28 45 views
2

我創建了XML文件作爲我創建的對象(稱爲「triple」)的數據庫。 當我嘗試添加新對象(同一類型的)的另一行時,它會刪除上一行。 如何添加而不刪除? (下前行)如何在Java中將對象添加到xml中?

下面是代碼:

public class RDB { 
    File file; 
    String filepath; 
    JAXBContext jaxbContext; 
    Marshaller jaxbMarshaller; 


    RDB(){ 
     filepath = "RDB.xml"; 
     file = new File(filepath);  
     StreamResult result = new StreamResult(file); 
     try { 
      jaxbContext = JAXBContext.newInstance(triple.class); 
      jaxbMarshaller = jaxbContext.createMarshaller(); 
     } catch (JAXBException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 


    void addToXml(triple t){ 
     try { 
      // output pretty printed 
      jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 

      jaxbMarshaller.marshal(t, file); 
      jaxbMarshaller.marshal(t, System.out); 

       } catch (JAXBException e) { 
      e.printStackTrace(); 
      } 
    } 


    public static void main(String argv[]) { 

     RDB r = new RDB(); 
     r.addToXml(new triple(1,2,3)); 
     r.addToXml(new triple(4,5,6)); 

    } 

與三階級是這樣的:

public class triple implements Serializable { 


    private static final long serialVersionUID = 1L; 
    private double x, y; 
    private int z; 

    triple(double x , double y, int z){ 
     this.x = x; 
     this.y = y; 
     this.z = z; 
    } 

謝謝!

+0

請使用Java命名約定,即「triple」類應該被命名爲「Triple」類。 –

回答

0

您每次編組一個對象。每次調用addToXml()時,都會覆蓋該文件。

請嘗試實現一個具有'triple'數組的類,然後編組該類。

+1

謝謝!好主意 –

+0

或者你可以在追加模式下打開文件:) – SomeDude

+0

@svasa我不知道是否可以在追加模式下打開一個二進制文件(在這種情況下是Apache POI)。我認爲這是不可能的。你有關於它的任何信息嗎?謝謝 –

0

使用FileOutputStream中寫入XML追加模式,如:

OutputStream out = FileOutputStream(file, true); 

然後用jaxbMarshaller.marshal(t, out);

確保正確關閉流在完成後。

相關問題