您可以逐個遍歷整個列表中的每個項目。您需要在Marshaller
上設置JAXB_FRAGMENT
屬性以防止XML頭被寫出。您只需爲此用例創建JAXBContext
和Marshaller
一次。
import java.io.FileOutputStream;
import java.util.*;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Element.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
List<Element> elements = new ArrayList<>();
elements.add(new Element());
elements.add(new Element());
try(FileOutputStream fos = new FileOutputStream("src/forum18509018/out.txt")) {
for(Element element : elements) {
marshaller.marshal(element, fos);
}
}
}
}
感謝你的反應,我不想這樣做,通過迭代列表以及它們編組到文件需要大量的時間,特別是當你有巨大的data.That的處理,爲什麼我要一次處理列表。有沒有更好的方法來做到這一點? – user964147
@ user964147 - 如果您創建了'JAXBContext'和'Marshaller',那麼爲什麼您會預期在將列表與N個項目編組在一起並編組N個項目之間會出現性能差異? –
我正在經歷它,如果您編組單個條目並將它們寫入文件並再次封送附加到該文件的其他條目,顯然需要比將一堆數據附加到文件更多的時間。 – user964147