1 | /*
|
---|
2 | * Copyright (C) 1997 by Pharos IP Pty Ltd
|
---|
3 | * All rights reserved.
|
---|
4 | * $Id: IOUtils.java 10737 2005-10-19 03:06:40Z kjdon $
|
---|
5 | */
|
---|
6 |
|
---|
7 | package au.com.pharos.io;
|
---|
8 |
|
---|
9 | import java.io.ByteArrayOutputStream;
|
---|
10 | import java.io.InputStream;
|
---|
11 | import java.io.OutputStream;
|
---|
12 | import java.io.IOException;
|
---|
13 |
|
---|
14 | /**
|
---|
15 | * Plumbing utilities for manipulating Java IO classes.
|
---|
16 | *
|
---|
17 | * <P>These utilities really ought to be part of the
|
---|
18 | * <CODE>java.io</CODE> package, but they're not. Since they're
|
---|
19 | * pretty useful, here they are.
|
---|
20 | *
|
---|
21 | * @version $Revision: 10737 $
|
---|
22 | * @author Martin Pool
|
---|
23 | **/
|
---|
24 | public class IOUtils {
|
---|
25 | /** Size of blocks to read during IO. **/
|
---|
26 | static public final int BLOCK_SIZE = 4<<10;
|
---|
27 |
|
---|
28 | static public void pumpStream(InputStream inStream,
|
---|
29 | OutputStream outStream,
|
---|
30 | int contentLength)
|
---|
31 | throws IOException
|
---|
32 | {
|
---|
33 | int readBytes = 0;
|
---|
34 | byte[] block = new byte[BLOCK_SIZE];
|
---|
35 | int blockBytes;
|
---|
36 | while (readBytes < contentLength
|
---|
37 | && (blockBytes = inStream.read(block)) > 0) {
|
---|
38 | readBytes += blockBytes;
|
---|
39 | outStream.write(block, 0, blockBytes);
|
---|
40 | }
|
---|
41 | }
|
---|
42 |
|
---|
43 | static public int pumpStream(InputStream inStream,
|
---|
44 | OutputStream outStream)
|
---|
45 | throws IOException
|
---|
46 | {
|
---|
47 | byte[] block = new byte[BLOCK_SIZE];
|
---|
48 | int blockBytes, readBytes = 0;
|
---|
49 | while ( (blockBytes = inStream.read(block)) > 0 ) {
|
---|
50 | outStream.write(block, 0, blockBytes);
|
---|
51 | readBytes += blockBytes;
|
---|
52 | }
|
---|
53 | return readBytes;
|
---|
54 | }
|
---|
55 |
|
---|
56 | /** Reads the entire contents of the stream into a
|
---|
57 | * newly-constructed byte array.
|
---|
58 | **/
|
---|
59 | static public byte[] readAll(InputStream inStream)
|
---|
60 | throws IOException
|
---|
61 | {
|
---|
62 | ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
|
---|
63 | pumpStream(inStream, byteStream);
|
---|
64 | byte[] buf = byteStream.toByteArray();
|
---|
65 | byteStream.close();
|
---|
66 | return buf;
|
---|
67 | }
|
---|
68 | }
|
---|