Reputation: 747
I have a problem writing a file to a xml. Here is how this element looks in xsd.
<xs:element name="File">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:base64Binary">
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
Here is my method to write:
private void writeFile (XMLStreamWriter2 sw, final InputStream is){
//is - inputstream from file
try {
OutputStream output = null;
InputStream input = new Base64InputStream(is, true);
int count;
int BUFFER_SIZE = 4000;
byte[] buffer = new byte[BUFFER_SIZE];
output = new FileOutputStream(new File("D:\\test.txt"));
while ((count = input.read(buffer)) != -1) {
output.write(buffer, 0, count);
sw.writeBinary(buffer, 0, count);
}
is.close();
input.close();
output.close();
} catch (XMLStreamException ex) {
Logger.getLogger(StaxFinal.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(StaxFinal.class.getName()).log(Level.SEVERE, null, ex);
}
}
The content of test.txt is valid base-64 string, while content of File
xml elements file is not (i'm checking with http://www.opinionatedgeek.com/dotnet/tools/base64decode/). why
EDIT
Trying to use this, but i get a lot of carriage-return symbols #xd;
private void writeFile (XMLStreamWriter sw, InputStream is){
//is - FileInputStream
Reader reader = new InputStreamReader(new Base64InputStream(is, true));
char[] buf = new char[4096];
int n;
while( (n = reader.read(buf)) >= 0 ) {
sw.writeCharacters(buf, 0, n-3 );
}
}
EDIT Method:
writeRaw(char[] chars, int i, int i1)
works fine. Strange, but woodstox's readElementAsBinary
reads and decodes base64 for me. Why writeBinary
doesn't write valid base64?
Anyways, thank you skaffman! You are awesome!
Upvotes: 2
Views: 1517
Reputation: 56
I assume you use the Base64InputStream from Apache Commons Codec. It also offers a constructor with four arguments, that can be used to turn off line breaks completely. Adjusting your method from the question you can write valid Base64 output like this:
private void writeFile (XMLStreamWriter sw, InputStream is){
//is - FileInputStream
Reader reader = new InputStreamReader(new Base64InputStream(is, true, -1, null));
char[] buf = new char[4096];
int n;
while( (n = reader.read(buf)) >= 0 ) {
sw.writeCharacters(buf, 0, n);
}
}
Upvotes: 1
Reputation: 117
Based on the javadoc of Base64InputStream: if you provide two parameters to the constructor (InputStream in, boolean doEncode) then it creates a Base64InputStream such that all data read is either Base64-encoded or Base64-decoded from the original provided InputStream. and doEncode - true if we should encode all data read from us, false if we should decode.
Because I am not sure of what your function should do, I can only recon this:
Upvotes: 0