01: /*
02: * @(#)TextReader.java 1.2 04/12/06
03: *
04: * Copyright (c) 2001-2004 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 org.pnuts.io;
10:
11: import pnuts.io.CharacterEncoding;
12: import pnuts.lang.*;
13: import java.io.*;
14: import java.net.URL;
15:
16: /*
17: * function readText(Reader|InputStream|String|File|URL {, encoding })
18: */
19: class TextReader {
20:
21: protected static Object getText(File file, String encoding,
22: Context context) throws IOException {
23: long size = file.length();
24: if (size > Integer.MAX_VALUE) {
25: throw new RuntimeException("too large");
26: } else {
27: return getText(new BufferedReader(CharacterEncoding
28: .getReader(new FileInputStream(file), encoding,
29: context)), (int) size / 2, true);
30: }
31: }
32:
33: protected static Object getText(Reader reader, boolean needToClose)
34: throws IOException {
35: return getText(reader, -1, needToClose);
36: }
37:
38: protected static Object getText(Reader reader, int hint,
39: boolean needToClose) throws IOException {
40: int n;
41: int isize = 512;
42:
43: if (hint > 0) {
44: isize = hint;
45: }
46: char[] buf = new char[8192];
47: StringWriter sw = new StringWriter(isize);
48: try {
49: while ((n = reader.read(buf, 0, buf.length)) != -1) {
50: sw.write(buf, 0, n);
51: }
52: return sw.toString();
53: } finally {
54: if (needToClose) {
55: reader.close();
56: }
57: }
58: }
59: }
|