01: /*
02: * @(#)writer.java 1.2 04/12/06
03: *
04: * Copyright (c) 1997-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.Context;
12: import pnuts.lang.PnutsFunction;
13: import pnuts.lang.PnutsException;
14: import org.pnuts.lib.PathHelper;
15: import pnuts.io.CharacterEncoding;
16: import java.io.OutputStream;
17: import java.io.IOException;
18: import java.io.UnsupportedEncodingException;
19: import java.io.Writer;
20: import java.io.PrintWriter;
21: import java.io.BufferedWriter;
22: import java.io.FileOutputStream;
23: import java.io.File;
24:
25: /*
26: * function writer(output {, encoding })
27: */
28: public class writer extends PnutsFunction {
29:
30: public writer() {
31: super ("writer");
32: }
33:
34: public boolean defined(int nargs) {
35: return nargs == 1 || nargs == 2;
36: }
37:
38: static PrintWriter getWriter(Object output, String enc,
39: Context context) throws IOException {
40: if (output instanceof PrintWriter) {
41: return (PrintWriter) output;
42: } else if (output instanceof Writer) {
43: return new PrintWriter((Writer) output);
44: } else if (output instanceof OutputStream) {
45: return new PrintWriter(new BufferedWriter(CharacterEncoding
46: .getWriter((OutputStream) output, enc, context)));
47: } else if (output instanceof File) {
48: File file = (File) output;
49: PathHelper.ensureBaseDirectory(file);
50: return new PrintWriter(new BufferedWriter(
51: CharacterEncoding.getWriter(new FileOutputStream(
52: file), enc, context)));
53: } else if (output instanceof String) {
54: File file = PathHelper.getFile((String) output, context);
55: PathHelper.ensureBaseDirectory(file);
56: return new PrintWriter(new BufferedWriter(
57: CharacterEncoding.getWriter(new FileOutputStream(
58: file), enc, context)));
59: } else {
60: throw new IllegalArgumentException(String.valueOf(output));
61: }
62: }
63:
64: protected Object exec(Object[] args, Context context) {
65: int nargs = args.length;
66: try {
67: if (nargs == 1) {
68: return getWriter(args[0], null, context);
69: } else if (nargs == 2) {
70: return getWriter(args[0], (String) args[1], context);
71: } else {
72: undefined(args, context);
73: return null;
74: }
75: } catch (IOException e) {
76: throw new PnutsException(e, context);
77: }
78: }
79:
80: public String toString() {
81: return "function writer((Writer|OutputStream|String|File) {, encoding } )";
82: }
83: }
|