01: /*
02: * @(#)Resource.java 1.2 04/12/06
03: *
04: * Copyright (c) 1997-2003 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package pnuts.lib;
10:
11: import java.net.URL;
12: import java.io.IOException;
13: import java.io.InputStream;
14:
15: abstract class Resource {
16: public abstract URL getURL();
17:
18: public abstract InputStream getInputStream() throws IOException;
19:
20: public abstract int getContentLength() throws IOException;
21:
22: public byte[] getBytes() throws IOException {
23: byte[] b;
24: InputStream in = getInputStream();
25: int len = getContentLength();
26: try {
27: if (len != -1) {
28: b = new byte[len];
29: while (len > 0) {
30: int n = in.read(b, b.length - len, len);
31: if (n == -1) {
32: throw new IOException("unexpected EOF");
33: }
34: len -= n;
35: }
36: } else {
37: b = new byte[1024];
38: int total = 0;
39: while ((len = in.read(b, total, b.length - total)) != -1) {
40: total += len;
41: if (total >= b.length) {
42: byte[] tmp = new byte[total * 2];
43: System.arraycopy(b, 0, tmp, 0, total);
44: b = tmp;
45: }
46: }
47: if (total != b.length) {
48: byte[] tmp = new byte[total];
49: System.arraycopy(b, 0, tmp, 0, total);
50: b = tmp;
51: }
52: }
53: } finally {
54: in.close();
55: }
56: return b;
57: }
58: }
|