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