01: /*
02: * @(#)writeText.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.lang.*;
12: import java.io.*;
13:
14: /*
15: * function writeText(text, String|File|OutputStream|Writer {, encoding })
16: */
17: public class writeText extends PnutsFunction {
18:
19: private final String WRITER_SYMBOL = "writer".intern();
20:
21: public writeText() {
22: super ("writeText");
23: }
24:
25: public boolean defined(int narg) {
26: return (narg == 2 || narg == 3);
27: }
28:
29: protected Object exec(Object args[], Context context) {
30: int narg = args.length;
31: if (narg != 2 && narg != 3) {
32: undefined(args, context);
33: return null;
34: }
35: String text = args[0].toString();
36: Object output = args[1];
37: Writer writer;
38: try {
39: if (output instanceof Writer) {
40: writer = (Writer) output;
41: writer.write(text);
42: } else if (output instanceof OutputStream) {
43: PnutsFunction writerFunc = (PnutsFunction) context
44: .resolveSymbol(WRITER_SYMBOL);
45: Object[] a = new Object[args.length - 1];
46: System.arraycopy(args, 1, a, 0, a.length);
47: writer = (Writer) writerFunc.call(a, context);
48: writer.write(text);
49: } else if ((output instanceof File)
50: || (output instanceof String)) {
51: PnutsFunction writerFunc = (PnutsFunction) context
52: .resolveSymbol(WRITER_SYMBOL);
53: Object[] a = new Object[args.length - 1];
54: System.arraycopy(args, 1, a, 0, a.length);
55: writer = (Writer) writerFunc.call(a, context);
56: writer.write(text);
57: writer.close();
58: } else {
59: throw new IllegalArgumentException(output.toString());
60: }
61: return null;
62: } catch (IOException e) {
63: throw new PnutsException(e, context);
64: }
65: }
66:
67: public String toString() {
68: return "function writeText(String, OutputStream|Writer|String|File {, encoding} )";
69: }
70: }
|