1 importorg.apache.commons.net.ftp.FTP;2 importorg.apache.commons.net.ftp.FTPClient;3 importorg.apache.commons.net.ftp.FTPFile;4 importorg.apache.commons.net.ftp.FTPReply;5
6 importjava.io.BufferedInputStream;7 importjava.io.BufferedOutputStream;8 importjava.io.File;9 importjava.io.FileInputStream;10 importjava.io.FileNotFoundException;11 importjava.io.FileOutputStream;12 importjava.io.IOException;13 importjava.io.InputStream;14 importjava.io.OutputStream;15 importjava.net.UnknownHostException;16 importjava.util.ArrayList;17 importjava.util.List;18
19 public classFtpUtil {20 public static final String ANONYMOUS_LOGIN = "anonymous";21 privateFTPClient ftp;22 private booleanis_connected;23
24 publicFtpUtil() {25 ftp = newFTPClient();26 is_connected = false;27 }28
29 public FtpUtil(int defaultTimeoutSecond, int connectTimeoutSecond, intdataTimeoutSecond){30 ftp = newFTPClient();31 is_connected = false;32
33 ftp.setDefaultTimeout(defaultTimeoutSecond * 1000);34 ftp.setConnectTimeout(connectTimeoutSecond * 1000);35 ftp.setDataTimeout(dataTimeoutSecond * 1000);36 }37
38 /**
39 * Connects to FTP server.40 *41 *@paramhost42 * FTP server address or name43 *@paramport44 * FTP server port45 *@paramuser46 * user name47 *@parampassword48 * user password49 *@paramisTextMode50 * text / binary mode switch51 *@throwsIOException52 * on I/O errors53 */
54 public void connect(String host, int port, String user, String password, boolean isTextMode) throwsIOException {55 //Connect to server.
56 try{57 ftp.connect(host, port);58 } catch(UnknownHostException ex) {59 throw new IOException("Can't find FTP server '" + host + "'");60 }61
62 //Check rsponse after connection attempt.
63 int reply =ftp.getReplyCode();64 if (!FTPReply.isPositiveCompletion(reply)) {65 disconnect();66 throw new IOException("Can't connect to server '" + host + "'");67 }68
69 if (user == "") {70 user =ANONYMOUS_LOGIN;71 }72
73 //Login.
74 if (!ftp.login(user, password)) {75 is_connected = false;76 disconnect();77 throw new IOException("Can't login to server '" + host + "'");78 } else{79 is_connected = true;80 }81
82 //Set data transfer mode.
83 if(isTextMode) {84 ftp.setFileType(FTP.ASCII_FILE_TYPE);85 } else{86 ftp.setFileType(FTP.BINARY_FILE_TYPE);87 }88 }89
90 /**
91 * Uploads the file to the FTP server.92 *93 *@paramftpFileName94 * server file name (with absolute path)95 *@paramlocalFile96 * local file to upload97 *@throwsIOException98 * on I/O errors99 */
100 public void upload(String ftpFileName, File localFile) throwsIOException {101 //File check.
102 if (!localFile.exists()) {103 throw new IOException("Can't upload '" + localFile.getAbsolutePath() + "'. This file doesn't exist.");104 }105
106 //Upload.
107 InputStream in = null;108 try{109
110 //Use passive mode to pass firewalls.
111 ftp.enterLocalPassiveMode();112
113 in = new BufferedInputStream(newFileInputStream(localFile));114 if (!ftp.storeFile(ftpFileName, in)) {115 throw new IOException("Can't upload file '" + ftpFileName + "' to FTP server. Check FTP permissions and path.");116 }117
118 } finally{119 try{120 in.close();121 } catch(IOException ex) {122 }123 }124 }125
126 /**
127 * Downloads the file from the FTP server.128 *129 *@paramftpFileName130 * server file name (with absolute path)131 *@paramlocalFile132 * local file to download into133 *@throwsIOException134 * on I/O errors135 */
136 public void download(String ftpFileName, File localFile) throwsIOException {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(newFileOutputStream(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 *@paramftpFileName177 * server file name (with absolute path)178 *@throwsIOException179 * on I/O errors180 */
181 public void remove(String ftpFileName) throwsIOException {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 *@paramfilePath191 * absolute path on the server192 *@returnfiles relative names list193 *@throwsIOException194 * on I/O errors195 */
196 public List list(String filePath) throwsIOException {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 returnfileList;212 }213
214 /**
215 * Sends an FTP Server site specific command216 *217 *@paramargs218 * site command arguments219 *@throwsIOException220 * on I/O errors221 */
222 public void sendSiteCommand(String args) throwsIOException {223 if(ftp.isConnected()) {224 try{225 ftp.sendSiteCommand(args);226 } catch(IOException ex) {227 }228 }229 }230
231 /**
232 * Disconnects from the FTP server233 *234 *@throwsIOException235 * on I/O errors236 */
237 public void disconnect() throwsIOException {238
239 if(ftp.isConnected()) {240 try{241 ftp.logout();242 ftp.disconnect();243 is_connected = false;244 } catch(IOException ex) {245 }246 }247 }248
249 /**
250 * Makes the full name of the file on the FTP server by joining its path and251 * the local file name.252 *253 *@paramftpPath254 * file path on the server255 *@paramlocalFile256 * local file257 *@returnfull name of the file on the FTP server258 */
259 publicString makeFTPFileName(String ftpPath, File localFile) {260 if (ftpPath == "") {261 returnlocalFile.getName();262 } else{263 String path =ftpPath.trim();264 if (path.charAt(path.length() - 1) != '/') {265 path = path + "/";266 }267
268 return path +localFile.getName();269 }270 }271
272 /**
273 * Test coonection to ftp server274 *275 *@returntrue, if connected276 */
277 public booleanisConnected() {278 returnis_connected;279 }280
281 /**
282 * Get current directory on ftp server283 *284 *@returncurrent directory285 */
286 publicString getWorkingDirectory() {287 if (!is_connected) {288 return "";289 }290
291 try{292 returnftp.printWorkingDirectory();293 } catch(IOException e) {294 }295
296 return "";297 }298
299 /**
300 * Set working directory on ftp server301 *302 *@paramdir303 * new working directory304 *@returntrue, if working directory changed305 */
306 public booleansetWorkingDirectory(String dir) {307 if (!is_connected) {308 return false;309 }310
311 try{312 returnftp.changeWorkingDirectory(dir);313 } catch(IOException e) {314 }315
316 return false;317 }318
319 /**
320 * Change working directory on ftp server to parent directory321 *322 *@returntrue, if working directory changed323 */
324 public booleansetParentDirectory() {325 if (!is_connected) {326 return false;327 }328
329 try{330 returnftp.changeToParentDirectory();331 } catch(IOException e) {332 }333
334 return false;335 }336
337 /**
338 * Get parent directory name on ftp server339 *340 *@returnparent directory341 */
342 publicString getParentDirectory() {343 if (!is_connected) {344 return "";345 }346
347 String w =getWorkingDirectory();348 setParentDirectory();349 String p =getWorkingDirectory();350 setWorkingDirectory(w);351
352 returnp;353 }354
355 /**
356 * Get directory contents on ftp server357 *358 *@paramfilePath359 * directory360 *@returnlist of FTPFileInfo structures361 *@throwsIOException362 */
363 public List listFiles(String filePath) throwsIOException {364 List fileList = new ArrayList();365
366 //Use passive mode to pass firewalls.
367 ftp.enterLocalPassiveMode();368 FTPFile[] ftpFiles =ftp.listFiles(filePath);369 int size = (ftpFiles == null) ? 0: ftpFiles.length;370 for (int i = 0; i < size; i++) {371 FTPFile ftpFile =ftpFiles[i];372 FfpFileInfo fi = newFfpFileInfo();373 fi.setName(ftpFile.getName());374 fi.setSize(ftpFile.getSize());375 fi.setTimestamp(ftpFile.getTimestamp());376 fi.setType(ftpFile.isDirectory());377 fileList.add(fi);378 }379
380 returnfileList;381 }382
383 /**
384 * Get file from ftp server into given output stream385 *386 *@paramftpFileName387 * file name on ftp server388 *@paramout389 * OutputStream390 *@throwsIOException391 */
392 public void getFile(String ftpFileName, OutputStream out) throwsIOException {393 try{394 //Use passive mode to pass firewalls.
395 ftp.enterLocalPassiveMode();396
397 //Get file info.
398 FTPFile[] fileInfoArray =ftp.listFiles(ftpFileName);399 if (fileInfoArray == null) {400 throw new FileNotFoundException("File '" + ftpFileName + "' was not found on FTP server.");401 }402
403 //Check file size.
404 FTPFile fileInfo = fileInfoArray[0];405 long size =fileInfo.getSize();406 if (size >Integer.MAX_VALUE) {407 throw new IOException("File '" + ftpFileName + "' is too large.");408 }409
410 //Download file.
411 if (!ftp.retrieveFile(ftpFileName, out)) {412 throw new IOException("Error loading file '" + ftpFileName + "' from FTP server. Check FTP permissions and path.");413 }414
415 out.flush();416
417 } finally{418 if (out != null) {419 try{420 out.close();421 } catch(IOException ex) {422 }423 }424 }425 }426
427 /**
428 * Put file on ftp server from given input stream429 *430 *@paramftpFileName431 * file name on ftp server432 *@paramin433 * InputStream434 *@throwsIOException435 */
436 public void putFile(String ftpFileName, InputStream in) throwsIOException {437 try{438 //Use passive mode to pass firewalls.
439 ftp.enterLocalPassiveMode();440
441 if (!ftp.storeFile(ftpFileName, in)) {442 throw new IOException("Can't upload file '" + ftpFileName + "' to FTP server. Check FTP permissions and path.");443 }444 } finally{445 try{446 in.close();447 } catch(IOException ex) {448 }449 }450 }451 }