Reputation: 41
Im developing a program where i receive an XML file as InputStream. I have to make some changes and then return it as OutputStream.
Here is my code:
public void execute (InputStream xmlEntrada, OutputStream xmlSalida) {
SAXBuilder saxBuilder = new SAXBuilder();
Document document;
String idDocCobro, idCobro;
String sociedad, ejercicio, numDocCobro;
try {
document = saxBuilder.build(xmlEntrada);
Element raiz = document.getRootElement();
List piDocCobros = raiz.getChildren("Pagos");
for (int i = 0; i < piDocCobros.size(); i++) {
Element nodePiDocCobros = (Element) piDocCobros.get(i);
sociedad = nodePiDocCobros.getChildText("Sociedad");
ejercicio = nodePiDocCobros.getChildText("Ejercicio");
numDocCobro = nodePiDocCobros.getChildText("NumDocumentoCobro");
idDocCobro = sociedad + ejercicio + numDocCobro + System.currentTimeMillis();
nodePiDocCobros.getChild("iddoccobro").setText(idDocCobro);
List piCobros = nodePiDocCobros.getChildren("Pago");
for (int y = 0; y < piCobros.size(); y++) {
Element nodePiCobros = (Element) piCobros.get(y);
nodePiCobros.getChild("iddoccobro").setText(idDocCobro);
idCobro = numDocCobro + System.currentTimeMillis();
nodePiCobros.getChild("idcobro").setText(idCobro);
List piDocumentosRel = nodePiCobros.getChild("DocumentosRelacionados").getChildren("DocumentoRelacionado");
for (int z = 0; z < piDocumentosRel.size(); z++) {
Element nodePiDocumentosRel = (Element) piDocumentosRel.get(z);
nodePiDocumentosRel.getChild("idcobro").setText(idCobro);
}
}
}
copy(xmlEntrada, xmlSalida);
} catch (JDOMException | IOException e) {
System.out.println(e.toString());
}
}
public static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
while (true) {
int bytesRead = in.read(buffer);
if (bytesRead == -1){
break;
}
out.write(buffer, 0, bytesRead);
}
}
My problem is when i try to read the XML in the function copy
because the stream is already closed, so i get an Exception. The stream closes itself when i use the saxBuilder.build
sentence at the beginning of the program. I can't save the text before in a byte[]
variable because i will modify it during the program.
Any idea?
Thank you so much in advance! :)
Upvotes: 0
Views: 536
Reputation: 41
As some of you told me, i was making a silly mistake. What i had to do is to pass the documento to OutputStream. I did that with the next piece of code:
XMLOutputter xmlcode = new XMLOutputter();
xmlcode.output(document, xmlSalida);
Thanks all for your help!
Upvotes: 0
Reputation: 2490
The InputStream you've read is not the object that contains the modification you made. Your modifications are inside the Document object.
That's what you need to send to the OutputStream.
Upvotes: 2