1 18 19 package org.apache.tools.ant.util; 20 21 import java.io.ByteArrayOutputStream ; 22 import java.io.IOException ; 23 import java.io.OutputStream ; 24 25 31 public abstract class LineOrientedOutputStream extends OutputStream { 32 33 34 private static final int INTIAL_SIZE = 132; 35 36 37 private static final int CR = 0x0d; 38 39 40 private static final int LF = 0x0a; 41 42 private ByteArrayOutputStream buffer 43 = new ByteArrayOutputStream (INTIAL_SIZE); 44 private boolean skip = false; 45 46 53 public final void write(int cc) throws IOException { 54 final byte c = (byte) cc; 55 if ((c == LF) || (c == CR)) { 56 if (!skip) { 57 processBuffer(); 58 } 59 } else { 60 buffer.write(cc); 61 } 62 skip = (c == CR); 63 } 64 65 69 public final void flush() throws IOException { 70 if (buffer.size() > 0) { 71 processBuffer(); 72 } 73 } 74 75 80 protected void processBuffer() throws IOException { 81 try { 82 processLine(buffer.toString()); 83 } finally { 84 buffer.reset(); 85 } 86 } 87 88 94 protected abstract void processLine(String line) throws IOException ; 95 96 100 public final void close() throws IOException { 101 if (buffer.size() > 0) { 102 processBuffer(); 103 } 104 super.close(); 105 } 106 107 116 public final void write(byte[] b, int off, int len) throws IOException { 117 int offset = off; 119 int blockStartOffset = offset; 120 int remaining = len; 121 while (remaining > 0) { 122 while (remaining > 0 && b[offset] != LF && b[offset] != CR) { 123 offset++; 124 remaining--; 125 } 126 int blockLength = offset - blockStartOffset; 128 if (blockLength > 0) { 129 buffer.write(b, blockStartOffset, blockLength); 130 } 131 while (remaining > 0 && (b[offset] == LF || b[offset] == CR)) { 132 write(b[offset]); 133 offset++; 134 remaining--; 135 } 136 blockStartOffset = offset; 137 } 138 } 139 140 } 141 | Popular Tags |