1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.xolite.utils;
17
18
19 import java.io.BufferedWriter;
20 import java.io.IOException;
21 import java.io.OutputStream;
22 import java.io.OutputStreamWriter;
23
24 import net.sf.xolite.XMLSerializable;
25 import net.sf.xolite.XMLSerializeException;
26 import net.sf.xolite.impl.FlowXMLSerializer;
27
28
29
30
31
32
33
34
35 public class StreamXMLSerializer extends FlowXMLSerializer {
36
37
38 private String writerEncoding;
39 private BufferedWriter writer;
40 private boolean autoCloseWriter = true;
41
42
43 public StreamXMLSerializer(OutputStream stream) throws IOException {
44 this(stream, "UTF-8");
45 }
46
47
48 public StreamXMLSerializer(OutputStream stream, String encoding) throws IOException {
49 writerEncoding = encoding;
50 writer = new BufferedWriter(new OutputStreamWriter(stream, encoding));
51 }
52
53
54 public void serializeObject(XMLSerializable serial) throws XMLSerializeException {
55 if (serial == null) throw new XMLSerializeException("Cannot serialize null object");
56 startDocument();
57 serial.serialize(this);
58 endDocument();
59 }
60
61
62 public boolean getAutoCloseWriter() {
63 return autoCloseWriter;
64 }
65
66
67 public void setAutoCloseWriter(boolean newAutoCloseWriter) {
68 autoCloseWriter = newAutoCloseWriter;
69 }
70
71
72
73
74
75 @Override
76 protected void startDocumentImpl() throws IOException {
77 writer.write("<?xml version=\"1.0\" encoding=\"");
78 writer.write(writerEncoding);
79 writer.write("\"?>");
80 if (isUsingLineBreaks()) writeNewLine();
81 }
82
83
84 @Override
85 protected void endDocumentImpl() throws IOException {
86 if (autoCloseWriter) writer.close();
87 else writer.flush();
88 }
89
90
91 @Override
92 protected void writeNewLine() throws IOException {
93 writer.newLine();
94 }
95
96
97 @Override
98 protected void writeString(String text) throws IOException {
99 writer.write(text);
100 }
101
102
103 @Override
104 protected void writeCharacter(char ch) throws IOException {
105 writer.write(ch);
106 }
107
108
109 }