Skip to content

Commit bad9fee

Browse files
committed
IO-152 - Add ByteArrayOutputStream.write(InputStream)
git-svn-id: https://svn.apache.org/repos/asf/commons/proper/io/trunk@609421 13f79535-47bb-0310-9956-ffa450edef68
1 parent da8e318 commit bad9fee

2 files changed

Lines changed: 37 additions & 1 deletion

File tree

src/java/org/apache/commons/io/output/ByteArrayOutputStream.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package org.apache.commons.io.output;
1818

1919
import java.io.IOException;
20+
import java.io.InputStream;
2021
import java.io.OutputStream;
2122
import java.io.UnsupportedEncodingException;
2223
import java.util.ArrayList;
@@ -172,6 +173,34 @@ public synchronized void write(int b) {
172173
count++;
173174
}
174175

176+
/**
177+
* Writes the entire contents of the specified input stream to this
178+
* byte stream. Bytes from the input stream are read directly into the
179+
* internal buffers of this streams.
180+
*
181+
* @param in the input stream to read from
182+
* @return total number of bytes read from the input stream
183+
* (and written to this stream)
184+
* @throws IOException if an I/O error occurs while reading the input stream
185+
* @since Commons IO 1.4
186+
*/
187+
public synchronized int write(InputStream in) throws IOException {
188+
int readCount = 0;
189+
int inBufferPos = count - filledBufferSum;
190+
int n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos);
191+
while (n != -1) {
192+
readCount += n;
193+
inBufferPos += n;
194+
count += n;
195+
if (inBufferPos == currentBuffer.length) {
196+
needNewBuffer(currentBuffer.length);
197+
inBufferPos = 0;
198+
}
199+
n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos);
200+
}
201+
return readCount;
202+
}
203+
175204
/**
176205
* @see java.io.ByteArrayOutputStream#size()
177206
*/

src/test/org/apache/commons/io/output/ByteArrayOutputStreamTestCase.java

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
*/
1717
package org.apache.commons.io.output;
1818

19+
import java.io.ByteArrayInputStream;
1920
import java.io.IOException;
2021

2122
import junit.framework.TestCase;
@@ -120,7 +121,13 @@ public void testStream() throws Exception {
120121
written = writeData(baout, ref, new int[] {5, 47, 33, 60, 1, 0, 8});
121122
assertEquals(155, written);
122123
checkStreams(baout, ref);
123-
124+
125+
//Test the readFrom(InputStream) method
126+
baout.reset();
127+
written = baout.write(new ByteArrayInputStream(ref.toByteArray()));
128+
assertEquals(155, written);
129+
checkStreams(baout, ref);
130+
124131
//Write the commons Byte[]OutputStream to a java.io.Byte[]OutputStream
125132
//and vice-versa to test the writeTo() method.
126133
ByteArrayOutputStream baout1 = new ByteArrayOutputStream(32);

0 commit comments

Comments
 (0)