KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > axis > utils > IOUtils


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.jboss.axis.utils;
18
19 import java.io.ByteArrayOutputStream JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.io.InputStream JavaDoc;
22
23 public class IOUtils
24 {
25    /**
26     * Helper method, just calls <tt>readFully(in, b, 0, b.length)</tt>
27     */

28    public static int readFully(InputStream JavaDoc in, byte[] b)
29            throws IOException JavaDoc
30    {
31       return readFully(in, b, 0, b.length);
32    }
33
34    /**
35     * Same as the normal <tt>in.read(b, off, len)</tt>, but tries to ensure that
36     * <p/>
37     * the entire len number of bytes is read.
38     * <p/>
39     * <p/>
40     * <p/>
41     * If the end of file is reached before any bytes are read, returns -1.
42     * <p/>
43     * Otherwise, returns the number of bytes read.
44     */

45    public static int readFully(InputStream JavaDoc in, byte[] b, int off, int len)
46            throws IOException JavaDoc
47    {
48       int total = 0;
49       for (; ;)
50       {
51          int got = in.read(b, off + total, len - total);
52          if (got < 0)
53          {
54             return (total == 0) ? -1 : total;
55          }
56          else
57          {
58             total += got;
59             if (total == len)
60                return total;
61          }
62       }
63    }
64
65    /** Copy the content of the given input stream to a byte array.
66     */

67    public static byte[] toByteArray(InputStream JavaDoc is)
68            throws IOException JavaDoc
69    {
70       ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc(1024);
71       byte[] bytes = new byte[1024];
72       int read = is.read(bytes);
73       while (read > 0)
74       {
75          baos.write(bytes, 0, read);
76          read = is.read(bytes);
77       }
78       bytes = baos.toByteArray();
79       return bytes;
80    }
81 }
Popular Tags