01: /*
02: * @(#)FileWriterHandler.java 1.2 04/12/06
03: *
04: * Copyright (c) 1997-2003 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 pnuts.compiler;
10:
11: import java.io.DataOutputStream;
12: import java.io.File;
13: import java.io.FileOutputStream;
14: import java.io.IOException;
15: import java.io.Serializable;
16:
17: /**
18: * This class is a concrete class of ClassFileHandler. When this is passed to
19: * Compiler.compile(..., ClassFileHandler), compiled class files are saved in
20: * the directory specified with the constructor.
21: */
22: public class FileWriterHandler implements ClassFileHandler,
23: Serializable {
24: private final static boolean DEBUG = false;
25:
26: private File dir;
27:
28: private boolean verbose;
29:
30: public FileWriterHandler(File dir) {
31: this .dir = dir;
32: }
33:
34: public void setVerbose(boolean flag) {
35: this .verbose = flag;
36: }
37:
38: protected void handleException(Exception e) {
39: e.printStackTrace();
40: }
41:
42: public Object handle(ClassFile cf) {
43: try {
44: write(cf, dir);
45: } catch (IOException e) {
46: handleException(e);
47: }
48: return null;
49: }
50:
51: void write(ClassFile cf, File base) throws IOException {
52: String className = cf.getClassName();
53: if (DEBUG) {
54: System.out.println("className " + className);
55: }
56: int idx = className.lastIndexOf('.');
57: File file = null;
58: if (idx > 0) {
59: String dirname = className.substring(0, idx).replace('.',
60: File.separatorChar);
61: File d = new File(base, dirname);
62: if (DEBUG) {
63: System.out.println("mkdir " + d);
64: }
65: d.mkdirs();
66: file = new File(d, className.substring(idx + 1) + ".class");
67: } else {
68: file = new File(base, className + ".class");
69: }
70: if (DEBUG) {
71: System.out.println("open " + file);
72: }
73: FileOutputStream fin = new FileOutputStream(file);
74: DataOutputStream dout = new DataOutputStream(fin);
75: cf.write(dout);
76: dout.close();
77: if (verbose) {
78: System.out.println(file);
79: }
80: }
81: }
|