1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.astrogrid.filestore.common.transfer ;
24
25 import java.io.InputStream ;
26 import java.io.OutputStream ;
27 import java.io.IOException ;
28
29 /***
30 * An toolkit to transfer bytes from one source to another.
31 * Initially this runs in-line, later refactoring may extend this to run in a separate thread.
32 *
33 */
34 public class TransferUtil
35 {
36
37 /***
38 * The size of our copy buffer (8k bytes).
39 *
40 */
41 private static final int BUFFER_SIZE = 8 * 1024 ;
42
43 /***
44 * Public constructor.
45 *
46 */
47 public TransferUtil(InputStream in, OutputStream out)
48 {
49 this.in = in ;
50 this.out = out ;
51 }
52
53 /***
54 * Our transfer buffer.
55 *
56 */
57 byte[] buffer = new byte[BUFFER_SIZE] ;
58
59 /***
60 * Our input stream.
61 *
62 */
63 private InputStream in ;
64
65 /***
66 * Our output stream.
67 *
68 */
69 private OutputStream out ;
70
71 /***
72 * The number of bytes transferred so far.
73 *
74 */
75 private int total ;
76
77 /***
78 * Access to our total.
79 *
80 */
81 public int getTotal()
82 {
83 return this.total ;
84 }
85
86 /***
87 * Transfer data from one stream to another.
88 * @return The number fo bytes transferred.
89 *
90 */
91 public int transfer()
92 throws IOException
93 {
94 int count = 0;
95 try {
96 do {
97 this.total += count ;
98 this.out.write(this.buffer, 0, count);
99 count = this.in.read(this.buffer, 0, this.buffer.length);
100 }
101 while (count != -1);
102 }
103 finally {
104 if (null != out)
105 {
106 this.out.close() ;
107 }
108 if (null != in)
109 {
110 this.in.close() ;
111 }
112 }
113 return this.total ;
114 }
115 }
116