KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > oddjob > io > FileType


1 /*
2  * Copyright (c) 2005, Rob Gordon.
3  */

4 package org.oddjob.io;
5
6 import java.io.File JavaDoc;
7 import java.io.FileInputStream JavaDoc;
8 import java.io.FileNotFoundException JavaDoc;
9 import java.io.InputStream JavaDoc;
10
11 import org.oddjob.OddjobException;
12
13 /**
14  * @oddjob.description Specify a file.
15  *
16  * @oddjob.example
17  * <pre>
18  * &lt;file file="foo.txt"/&gt;
19  * </pre>
20  * @author Rob Gordon.
21  */

22 public class FileType {
23
24     /**
25      * @oddjob.property
26      * @oddjob.description The file.
27      * @oddjob.required Yes.
28      */

29     private File JavaDoc file;
30         
31     /**
32      * Set the file.
33      *
34      * @param file The file.
35      */

36     public void setFile(File JavaDoc file) {
37         this.file = file;
38     }
39     
40     /**
41      * Get the value.
42      *
43      * @return The value.
44      */

45     public Object JavaDoc valueFor(Class JavaDoc required)
46     throws ClassCastException JavaDoc {
47         if (required == null) {
48             required = File JavaDoc.class;
49         }
50         if (required.isAssignableFrom(File JavaDoc.class)) {
51             return file;
52         }
53         if (required.isAssignableFrom(InputStream JavaDoc.class)) {
54             try {
55                 return new FileInputStream JavaDoc(file);
56             } catch (FileNotFoundException JavaDoc e) {
57                 throw new OddjobException("Failed to open file for input.");
58             }
59         }
60         if (required.isAssignableFrom(InputStream JavaDoc.class)) {
61             try {
62                 return new FileInputStream JavaDoc(file);
63             } catch (FileNotFoundException JavaDoc e) {
64                 throw new OddjobException("Failed to open file for output.");
65             }
66         }
67         if (required.isAssignableFrom(String JavaDoc.class)) {
68             return file.toString();
69         }
70         
71         throw new ClassCastException JavaDoc("Can not convert a File to " + required);
72     }
73     
74     public String JavaDoc toString() {
75         return (String JavaDoc) valueFor(String JavaDoc.class);
76     }
77 }
78
Popular Tags