1 27 28 package gnu.mail.providers.mbox; 29 30 import java.io.*; 31 32 39 class MboxOutputStream 40 extends FilterOutputStream 41 { 42 43 private static byte KET = 62; 44 45 48 protected byte buf[]; 49 50 53 protected int count = 0; 54 55 59 public MboxOutputStream(OutputStream out) 60 { 61 this(out, 1024); 62 } 63 64 69 public MboxOutputStream(OutputStream out, int len) 70 { 71 super(out); 72 buf = new byte[len]; 73 } 74 75 78 protected void validateAndFlushBuffer() 79 throws IOException 80 { 81 if (count > 0) 82 { 83 boolean done = false; 84 for (int i=0; i<count-5 && !done; i++) 85 { 86 if (buf[i]=='F' && 87 buf[i+1]=='r' && 88 buf[i+2]=='o' && 89 buf[i+3]=='m' && 90 buf[i+4]==' ') 91 { 92 byte[] b2 = new byte[buf.length+1]; 93 System.arraycopy(buf, 0, b2, 0, buf.length); 94 b2[i] = KET; 95 System.arraycopy(buf, i, b2, i+1, buf.length-i); 96 buf = b2; 97 count++; 98 done = true; 99 } 100 else if (buf[i]!=KET && buf[i]!='\n') 101 { 102 done = true; 103 } 104 } 105 out.write(buf, 0, count); 106 count = 0; 107 } 108 } 109 110 113 public synchronized void write(int b) 114 throws IOException 115 { 116 if (b=='\r') 117 return; 118 if (count>buf.length) 119 validateAndFlushBuffer(); 120 buf[count++] = (byte)b; 121 if (b=='\n') 122 validateAndFlushBuffer(); 123 } 124 125 129 public synchronized void write(byte b[], int off, int len) 130 throws IOException 131 { 132 for (int i=off; i<off+len; i++) 134 { 135 if (b[i]=='\r') 136 { 137 byte[] b2 = new byte[b.length-1]; 138 System.arraycopy(b, off, b2, off, len-1); 139 System.arraycopy(b, i+1, b2, i, len-(i-off)-1); 140 b = b2; 141 len--; 142 i--; 143 } 144 } 145 for (int i=off; i<off+len; i++) 147 { 148 if (b[i]=='\n' || i-off>buf.length) 149 { 150 int cl = (i-off>buf.length) ? buf.length : i-off; 151 System.arraycopy(b, off, buf, count, cl); 152 count += cl; 153 validateAndFlushBuffer(); 154 len = len-(i-off); 155 byte[] b2 = new byte[b.length]; 156 System.arraycopy(b, i, b2, off, len); 157 b = b2; 158 i = off; 159 } 160 } 161 System.arraycopy(b, off, buf, count, len); 162 count += len; 163 } 164 165 168 public synchronized void flush() 169 throws IOException 170 { 171 validateAndFlushBuffer(); 172 out.flush(); 173 } 174 175 } 176 | Popular Tags |