01: /*
02: * @(#)readText.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 org.pnuts.lib.PathHelper;
14: import java.io.*;
15: import java.net.URL;
16:
17: /*
18: * function readText(Reader|InputStream|String|File|URL {, encoding })
19: */
20: public class readText extends PnutsFunction {
21:
22: public readText() {
23: super ("readText");
24: }
25:
26: public boolean defined(int narg) {
27: return (narg == 1 || narg == 2);
28: }
29:
30: protected Object exec(Object args[], Context context) {
31: int narg = args.length;
32: if (narg != 1 && narg != 2) {
33: undefined(args, context);
34: return null;
35: }
36: Reader reader;
37: StringWriter sw = new StringWriter();
38: char[] buf;
39: int n;
40: Object input = args[0];
41: try {
42: if (input instanceof Reader) {
43: return TextReader.getText((Reader) input, false);
44: } else if (input instanceof InputStream) {
45: reader = CharacterEncoding.getReader(
46: (InputStream) input, context);
47: return TextReader.getText(reader, false);
48: } else if (input instanceof String) {
49: File f = new File((String) input);
50: if (args.length == 2) {
51: return TextReader.getText(f, (String) args[1],
52: context);
53: } else {
54: InputStream in = new FileInputStream(PathHelper
55: .getFile((String) input, context));
56: reader = CharacterEncoding.getReader(in, context);
57: return TextReader.getText(reader,
58: (int) (f.length() / 2), true);
59: }
60: } else if (input instanceof File) {
61: File f = (File) input;
62: if (args.length == 2) {
63: return TextReader.getText(f, (String) args[1],
64: context);
65: } else {
66: InputStream in = new FileInputStream(f);
67: reader = CharacterEncoding.getReader(in, context);
68: return TextReader.getText(reader,
69: (int) (f.length() / 2), true);
70: }
71: } else if (input instanceof URL) {
72: URL url = (URL) input;
73: if (args.length == 2) {
74: return TextReader.getText(new InputStreamReader(url
75: .openStream(), (String) args[1]), true);
76: } else {
77: reader = URLHelper.getReader((URL) input, context);
78: return TextReader.getText(reader, true);
79: }
80: } else {
81: throw new IllegalArgumentException(String
82: .valueOf(input));
83: }
84: } catch (IOException e) {
85: throw new PnutsException(e, context);
86: }
87: }
88:
89: public String toString() {
90: return "function readText(InputStream|Reader|String|File|URL {, encoding })";
91: }
92: }
|