01: /*
02: * @(#)writeObject.java 1.1 05/06/14
03: *
04: * Copyright (c) 1997-2005 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 org.pnuts.lib.PathHelper;
13: import java.io.*;
14:
15: /*
16: * writeObject(object, fileOrStream)
17: */
18: public class writeObject extends PnutsFunction {
19:
20: public writeObject() {
21: super ("writeObject");
22: }
23:
24: public boolean defined(int narg) {
25: return narg == 2;
26: }
27:
28: protected Object exec(Object[] args, Context context) {
29: int nargs = args.length;
30: if (nargs != 2) {
31: undefined(args, context);
32: return null;
33: }
34: Object arg0 = args[0];
35: Object arg1 = args[1];
36: ObjectOutputStream out;
37: OutputStream toClose = null;
38: try {
39: if (arg1 instanceof OutputStream) {
40: out = new ObjectOutputStream((OutputStream) arg1);
41: } else if (arg1 instanceof File) {
42: toClose = new FileOutputStream((File) arg1);
43: out = new ObjectOutputStream(toClose);
44: } else if (arg1 instanceof String) {
45: toClose = new FileOutputStream(PathHelper.getFile(
46: (String) arg1, context));
47: out = new ObjectOutputStream(toClose);
48: } else {
49: throw new IllegalArgumentException(String.valueOf(arg1));
50: }
51: out.writeObject(arg0);
52: return null;
53: } catch (IOException ioe) {
54: throw new PnutsException(ioe, context);
55: } finally {
56: if (toClose != null) {
57: try {
58: toClose.close();
59: } catch (IOException e) {
60: }
61: }
62: }
63: }
64:
65: public String toString() {
66: return "function writeObject(obj, OutputStream|String|File)";
67: }
68: }
|