1. 获取FTP连接
/** * 获取FTP连接 * * @param hostname FTP IP地址 * @param port FTP端口号 * @param username FTP用户名 * @param password FTP密码 * @return */ public static FTPClient getFTPClient(final String hostname, final int port, final String username, final String password) { log.info("get ftpClient hostname=" + hostname + ", port=" + port + ", username=" + username); FTPClient ftpClient = null; final FTPClientConfig config = new FTPClientConfig(); config.setHost(hostname); config.setPort(port); config.setUsername(username); config.setPassword(password); config.setEncoding(ScanConstant.ENCODING_UTF_8); factory = new FTPClientFactory(config); try { pool = new FTPClientPool(factory); ftpClient = pool.borrowObject(); } catch (final Exception e1) { log.error("FTP连接池异常", e1); } // 设置缓冲区 ftpClient.setBufferSize(BUFFER_SIZE);//之前没有加这一项,总是获取失败 try { if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) { // 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK). LOCAL_CHARSET = "UTF-8"; } } catch (final IOException e1) { throw new FtpException("Set sendCommand UTF8 failed."); } // 设置编码 ftpClient.setControlEncoding(LOCAL_CHARSET); // 设置被动模式 ftpClient.enterLocalPassiveMode(); try { // 设置文件传输类型 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); } catch (final IOException e) { throw new FtpException("Fail to set file Type."); } try { ftpClient.setConnectTimeout(60000); } catch (final Exception e) { throw new FtpException("Set client timeout error."); } log.info("return ftpClient " + ftpClient); return ftpClient; }2. 上传文件
public static boolean uploadFile(final String hostname, final int port, final String username, final String password, final String fileName, final String path, final InputStream in) {
//fileName:文件名称 path:文件所在目录 in:文件输入流boolean success = false; final FTPClient ftpClient = getFTPClient(hostname, port, username, password); // 获取绝对路径 final String absPath = path; log.info("FTP 上传文件中。。。fileName=" + fileName); try { // 创建文件目录 createDirectory(ftpClient, absPath); // 更改目录 ftpClient.changeWorkingDirectory(absPath); success = ftpClient.storeFile(new String(fileName.getBytes("UTF-8"), "ISO-8859-1"), in); if (!success) { log.info("failed to upload file."); } } catch (final IOException e) { log.error("failed to upload file.", e); } finally { if (in != null) { try { in.close(); } catch (final IOException e) { log.error("failed to close inputStream.", e); } } if (ftpClient != null) { disconnec(ftpClient); } } log.info("FTP文件上传结束。"); return success; }
3. 下载文件
/** * @param hostname FTP IP * @param port FTP端口 * @param username FTP用户名 * @param password FTP 密码 * @param ftpPath FTP服务器中文件所在路径 格式: ftptest/aa/a.txt */ public static boolean downloadFile(final String hostname, final int port, final String username, final String password, final String ftpPath, final HttpServletResponse response, final String scanFileName) { log.info("to download file from FTP: " + ftpPath); boolean downloaded = false; FTPClient ftpClient = null; OutputStream outputStream = null; try { outputStream = response.getOutputStream(); response.reset(); response.setCharacterEncoding(ScanConstant.ENCODING_UTF_8); response.setContentType("application/octet-stream"); response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(scanFileName, "UTF-8")); ftpClient = getFTPClient(hostname, port, username, password); downloaded = ftpClient.retrieveFile( new String(ftpPath.getBytes("UTF-8"), "IOS-8859-1"), outputStream); outputStream.flush(); } catch (final IOException e) { log.error("download file failed! ftpFile = " + ftpPath + "/" + ftpPath, e); } finally { if (outputStream != null) { try { outputStream.close(); } catch (final IOException e) { log.error("failed to close outputStream!", e); } } if (ftpClient != null) { disconnec(ftpClient); } } log.info("downloaded file from FTP!"); return downloaded; }
4. 关闭连接
public static void disconnec(final FTPClient ftpClient) { log.info("断开ftp连接: " + ftpClient); try { ftpClient.logout(); } catch (final IOException e) { log.error("ftp failed to log out from server.", e); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (final IOException e) { log.error("Failed to disconnect from server.", e); } } } log.info("ftp断开连接成功!"); }
获取项目路径
System.getProperty("user.dir")
5. 判断文件是否存在
/** * 检验指定路径的文件是否存在ftp服务器中 * @param filePath--指定绝对路径的文件 * @return */ public static boolean isFTPFileExist(final String hostname, final int port, final String username, final String password, final String filePath) { log.info("判断文件在ftp上是否存在!"); boolean exists = false; final FTPClient ftpClient = FtpForSoftScan.getFTPClient(hostname, port, username, password); try { final FTPFile[] files = ftpClient.listFiles(new String(filePath.getBytes("UTF-8"), "ISO-8859-1")); if (files != null && files.length > 0) { exists = true; } } catch (final IOException e) { log.error("failed to judge whether the file (" + filePath + ") is existed"); } log.info("文件" + filePath + "在ftp上是否存在?" + exists); return exists; }
6. 删除文件
public static boolean deleteFile (final String hostname, final int port, final String username, final String password, final String ftpPath) { if (ftpPath != null && ftpPath != "") { final FTPClient ftpClient = getFTPClient(hostname, port, username, password); if (ftpPath.endsWith("/")) { log.info("错误的文件路径"); return false; } try { final boolean exists = isFTPFileExist(hostname, port, username, password, ftpPath); if (exists) { ftpClient.deleteFile(new String(ftpPath.getBytes(ScanConstant.ENCODING_UTF_8), ScanConstant.SERVER_CHARSET_IOS)); } else { log.info("文件" + ftpPath + "已经不存在"); return true; } } catch (IOException e) { log.error("FTP上文件删除失败!", e); return false; } } else { log.info("没有需要删除的文件!"); } return true; }