1 7 8 package org.apache.jetspeed.util; 9 10 import java.io.ByteArrayOutputStream ; 11 import java.io.InputStream ; 12 import java.io.IOException ; 13 import java.io.InputStreamReader ; 14 import java.io.OutputStream ; 15 import java.io.OutputStreamWriter ; 16 import java.io.Reader ; 17 import java.io.Writer ; 18 19 25 public class Streams 26 { 27 static final int BLOCK_SIZE=4096; 28 29 public static void drain(InputStream r,OutputStream w) throws IOException 30 { 31 byte[] bytes=new byte[BLOCK_SIZE]; 32 try 33 { 34 int length=r.read(bytes); 35 while(length!=-1) 36 { 37 if(length!=0) 38 { 39 w.write(bytes,0,length); 40 } 41 length=r.read(bytes); 42 } 43 } 44 finally 45 { 46 bytes=null; 47 } 48 49 } 50 51 public static void drain(Reader r,Writer w) throws IOException 52 { 53 char[] bytes=new char[BLOCK_SIZE]; 54 try 55 { 56 int length=r.read(bytes); 57 while(length!=-1) 58 { 59 if(length!=0) 60 { 61 w.write(bytes,0,length); 62 } 63 length=r.read(bytes); 64 } 65 } 66 finally 67 { 68 bytes=null; 69 } 70 71 } 72 73 public static void drain(Reader r,OutputStream os) throws IOException 74 { 75 Writer w=new OutputStreamWriter (os); 76 drain(r,w); 77 w.flush(); 78 } 79 80 public static byte[] drain(InputStream r) throws IOException 81 { 82 ByteArrayOutputStream bytes=new ByteArrayOutputStream (); 83 drain(r,bytes); 84 return bytes.toByteArray(); 85 } 86 87 public static void drain(InputStream is, Writer w) throws IOException 88 { 89 Reader r = new InputStreamReader (is); 90 drain(r,w); 91 w.flush(); 92 } 93 94 public static String getAsString(InputStream is) 95 { 96 int c=0; 97 char lineBuffer[]=new char[128], buf[]=lineBuffer; 98 int room= buf.length, offset=0; 99 try 100 { 101 loop: while (true) 102 { 103 switch (c = is.read() ) 105 { 106 case -1: break loop; 107 108 default: if (--room < 0) 109 { 110 buf = new char[offset + 128]; 111 room = buf.length - offset - 1; 112 System.arraycopy(lineBuffer, 0, 113 buf, 0, offset); 114 lineBuffer = buf; 115 } 116 buf[offset++] = (char) c; 117 break; 118 } 119 } 120 } 121 catch(IOException ioe) 122 { 123 ioe.printStackTrace(); 124 } 125 if ((c == -1) && (offset == 0)) 126 { 127 return null; 128 } 129 return String.copyValueOf(buf, 0, offset); 130 } 131 132 public static String getAsString(Reader is) 133 { 134 int c=0; 135 char lineBuffer[]=new char[128], buf[]=lineBuffer; 136 int room= buf.length, offset=0; 137 try 138 { 139 loop: while (true) 140 { 141 switch (c = is.read() ) 143 { 144 case -1: break loop; 145 146 default: if (--room < 0) 147 { 148 buf = new char[offset + 128]; 149 room = buf.length - offset - 1; 150 System.arraycopy(lineBuffer, 0, 151 buf, 0, offset); 152 lineBuffer = buf; 153 } 154 buf[offset++] = (char) c; 155 break; 156 } 157 } 158 } 159 catch(IOException ioe) 160 { 161 ioe.printStackTrace(); 162 } 163 if ((c == -1) && (offset == 0)) 164 { 165 return null; 166 } 167 return String.copyValueOf(buf, 0, offset); 168 } 169 170 171 172 } 173 174 | Popular Tags |