Debian Codegraph @

src/main/java/org/freehep/util/io/ASCIIHexOutputStream.java

raw
1 // Copyright 2001, FreeHEP.
2 package org.freehep.util.io;
3
4 import java.io.FilterOutputStream;
5 import java.io.IOException;
6 import java.io.OutputStream;
7
8 /**
9 * The ASCIIHexOutputStream encodes binary data as ASCII Hexadecimal. The exact
10 * definition of ASCII Hex encoding can be found in the PostScript Language
11 * Reference (3rd ed.) chapter 3.13.3.
12 *
13 * @author Mark Donszelmann
14 * @version $Id: ASCIIHexOutputStream.java 8584 2006-08-10 23:06:37Z duns $
15 */
16 public class ASCIIHexOutputStream extends FilterOutputStream implements
17 FinishableOutputStream {
18
19 private final static int MAX_CHARS_PER_LINE = 80;
20
21 private int characters;
22
23 private boolean end;
24
25 private String newline = "\n";
26
27 /**
28 * Create an ASCIIHex Output Stream for given stream.
29 *
30 * @param out output stream to use
31 */
32 public ASCIIHexOutputStream(OutputStream out) {
33 super(out);
34 characters = MAX_CHARS_PER_LINE;
35 end = false;
36 try {
37 newline = System.getProperty("line.separator");
38 } catch (SecurityException e) {
39 // ignored;
40 }
41 }
42
43 public void write(int b) throws IOException {
44 String s = Integer.toHexString(b & 0x00FF);
45 switch (s.length()) {
46 case 1:
47 writeChar('0');
48 writeChar(s.charAt(0));
49 break;
50 case 2:
51 writeChar(s.charAt(0));
52 writeChar(s.charAt(1));
53 break;
54 default:
55 throw new IOException("ASCIIHexOutputStream: byte '" + b
56 + "' was encoded in less than 1 or more than 2 chars");
57 }
58 }
59
60 public void finish() throws IOException {
61 if (!end) {
62 end = true;
63 writeChar('>');
64 writeNewLine();
65 flush();
66 if (out instanceof FinishableOutputStream) {
67 ((FinishableOutputStream) out).finish();
68 }
69 }
70 }
71
72 public void close() throws IOException {
73 finish();
74 super.close();
75 }
76
77 private void writeChar(int b) throws IOException {
78 if (characters == 0) {
79 characters = MAX_CHARS_PER_LINE;
80 writeNewLine();
81 }
82 characters--;
83 super.write(b);
84 }
85
86 private void writeNewLine() throws IOException {
87 // write a newline
88 for (int i=0; i < newline.length(); i++) {
89 super.write(newline.charAt(i));
90 }
91 }
92 }