[JAVA]Apache FTPClient操作“卡死”问题的分析和解决(三)

2014-11-24 07:32:03 · 作者: · 浏览: 2
137 // Download.
138 OutputStream out = null;
139 try {
140 // Use passive mode to pass firewalls.
141 ftp.enterLocalPassiveMode();
142
143 // Get file info.
144 FTPFile[] fileInfoArray = ftp.listFiles(ftpFileName);
145 if (fileInfoArray == null) {
146 throw new FileNotFoundException("File " + ftpFileName + " was not found on FTP server.");
147 }
148
149 // Check file size.
150 FTPFile fileInfo = fileInfoArray[0];
151 long size = fileInfo.getSize();
152 if (size > Integer.MAX_VALUE) {
153 throw new IOException("File " + ftpFileName + " is too large.");
154 }
155
156 // Download file.
157 out = new BufferedOutputStream(new FileOutputStream(localFile));
158 if (!ftp.retrieveFile(ftpFileName, out)) {
159 throw new IOException("Error loading file " + ftpFileName + " from FTP server. Check FTP permissions and path.");
160 }
161
162 out.flush();
163 } finally {
164 if (out != null) {
165 try {
166 out.close();
167 } catch (IOException ex) {
168 }
169 }
170 }
171 }
172
173 /**
174 * Removes the file from the FTP server.
175 *
176 * @param ftpFileName
177 * server file name (with absolute path)
178 * @throws IOException
179 * on I/O errors
180 */
181 public void remove(String ftpFileName) throws IOException {
182 if (!ftp.deleteFile(ftpFileName)) {
183 throw new IOException("Can't remove file '" + ftpFileName + "' from FTP server.");
184 }
185 }
186
187 /**
188 * Lists the files in the given FTP directory.
189 *
190 * @param filePath
191 * absolute path on the server
192 * @return files relative names list
193 * @throws IOException
194 * on I/O errors
195 */
196 public List list(String filePath) throws IOException {
197 List fileList = new ArrayList();
198
199 // Use passive mode to pass firewalls.
200 ftp.enterLocalPassiveMode();
201
202 FTPFile[] ftpFiles = ftp.listFiles(filePath);
203 int size = (ftpFiles == null) 0 : ftpFiles.length;
204 for (int i = 0; i < size; i++) {
205 FTPFile ftpFile = ftpFiles[i];
206 if (ftpFile.isFile()) {
207 fileList.add(ftpFile.getName());
208 }
209 }
210
211 return fileList;
212 }
213
214 /**
215 * Sends an FTP Server site specific command
216 *
217 * @param args
218 * site command arguments
219 * @throws IOException
220 * on I/O errors
221 */
222 public void sendSiteCommand(String args) throws IOException {
223 if (ftp.isConnected()) {
224 try {
225 ftp.sendSiteCommand(args);
226 } catch (IOException ex) {
227 }
228 }
229 }
230
231 /**
232 * Disconnects from the FTP server
233 *
234 * @throws IOException
235 * on I/O errors
236 */
237 public void disconnect() throws IOException {
238
239 if (ftp.isConnected()) {
240 try {
241 ftp.logout();
242 ftp.disconnect();
243 is