1
2
3
4
5
6
7
8
9
10
11 package org.astrogrid.io;
12
13 import org.apache.commons.logging.Log;
14 import org.apache.commons.logging.LogFactory;
15
16 import java.io.*;
17
18 /***
19 * Helper class for connecting streams
20 *
21 * @author M Hill
22 */
23
24 public class Piper
25 {
26 /***
27 * Logger for this class
28 */
29 private static final Log logger = LogFactory.getLog(Piper.class);
30
31 private static final int BLOCK_SIZE = 2048;
32 /*** level above which warnings will be issued about transfer sizes*/
33 private static final int EXCESSIVE_SIZE_WARNING_LEVEL=1024*1024*30;
34
35 /*** Utility class - should not be instantiated */
36 private Piper() {}
37
38 /***
39 * Helper method for reading all the bytes from the given input stream
40 * and sending them to the given output stream. Remember that it is much
41 * more efficient to use Buffered streams. @see bufferedPipe.
42 */
43 public static void pipe(InputStream in, OutputStream out) throws IOException
44 {
45 byte[] block = new byte[BLOCK_SIZE];
46 int ibytes = 0;
47 int imult = 1;
48 int read = in.read(block);
49 ibytes += read;
50 while (read > -1)
51 {
52 out.write(block,0, read);
53 read = in.read(block);
54 ibytes += read;
55 if(ibytes > imult * EXCESSIVE_SIZE_WARNING_LEVEL)
56 {
57 logger.warn("pipe has read "+ibytes);
58 imult++;
59 }
60 }
61 }
62
63 /*** Convenience routine to wrap given streams in Buffered*putStreams and
64 * pipe
65 */
66 public static void bufferedPipe(InputStream in, OutputStream out) throws IOException
67 {
68 out = new BufferedOutputStream(out);
69 pipe(new BufferedInputStream(in), out);
70 out.flush();
71
72 }
73
74
75 /***
76 * Helper method for reading all the bytes from the given reader
77 * and sending them to the given writer.
78 */
79 public static void pipe(Reader in, Writer out) throws IOException
80 {
81 char[] block = new char[BLOCK_SIZE];
82 int ichar = 0;
83 int imult = 1;
84 int read = in.read(block);
85 ichar += read;
86 while (read > -1)
87 {
88 out.write(block,0, read);
89 read = in.read(block);
90 ichar += read;
91 if(ichar > imult * EXCESSIVE_SIZE_WARNING_LEVEL)
92 {
93 logger.warn("piper has read "+ ichar);
94 imult++;
95 }
96 }
97 }
98
99 /***
100 * Convenience routine to wrap given readers/writers in Buffereds
101 */
102 public static void bufferedPipe(Reader in, Writer out) throws IOException
103 {
104 out = new BufferedWriter(out);
105 pipe(new BufferedReader(in), out);
106 out.flush();
107 }
108
109 }
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126