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