1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 package org.apache.commons.httpclient.methods.multipart;
31
32 import java.io.ByteArrayInputStream;
33 import java.io.File;
34 import java.io.FileInputStream;
35 import java.io.FileNotFoundException;
36 import java.io.IOException;
37 import java.io.InputStream;
38
39 /***
40 * A PartSource that reads from a File.
41 *
42 * @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
43 * @author <a href="mailto:mdiggory@latte.harvard.edu">Mark Diggory</a>
44 * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
45 *
46 * @since 2.0
47 */
48 public class FilePartSource implements PartSource {
49
50 /*** File part file. */
51 private File file = null;
52
53 /*** File part file name. */
54 private String fileName = null;
55
56 /***
57 * Constructor for FilePartSource.
58 *
59 * @param file the FilePart source File.
60 *
61 * @throws FileNotFoundException if the file does not exist or
62 * cannot be read
63 */
64 public FilePartSource(File file) throws FileNotFoundException {
65 this.file = file;
66 if (file != null) {
67 if (!file.isFile()) {
68 throw new FileNotFoundException("File is not a normal file.");
69 }
70 if (!file.canRead()) {
71 throw new FileNotFoundException("File is not readable.");
72 }
73 this.fileName = file.getName();
74 }
75 }
76
77 /***
78 * Constructor for FilePartSource.
79 *
80 * @param fileName the file name of the FilePart
81 * @param file the source File for the FilePart
82 *
83 * @throws FileNotFoundException if the file does not exist or
84 * cannot be read
85 */
86 public FilePartSource(String fileName, File file)
87 throws FileNotFoundException {
88 this(file);
89 if (fileName != null) {
90 this.fileName = fileName;
91 }
92 }
93
94 /***
95 * Return the length of the file
96 * @return the length of the file.
97 * @see PartSource#getLength()
98 */
99 public long getLength() {
100 if (this.file != null) {
101 return this.file.length();
102 } else {
103 return 0;
104 }
105 }
106
107 /***
108 * Return the current filename
109 * @return the filename.
110 * @see PartSource#getFileName()
111 */
112 public String getFileName() {
113 return (fileName == null) ? "noname" : fileName;
114 }
115
116 /***
117 * Return a new {@link FileInputStream} for the current filename.
118 * @return the new input stream.
119 * @throws IOException If an IO problem occurs.
120 * @see PartSource#createInputStream()
121 */
122 public InputStream createInputStream() throws IOException {
123 if (this.file != null) {
124 return new FileInputStream(this.file);
125 } else {
126 return new ByteArrayInputStream(new byte[] {});
127 }
128 }
129
130 }