/** * Description: 从FTP服务器下载指定文件夹下的所有文件 * * @param url FTP服务器hostname * @param port FTP服务器端口 * @param username FTP登录账号 * @param password FTP登录密码 * @param remotePath FTP服务器上的相对路径 * @param localPath 下载后保存到本地的路径 * @param fileName 保存为该文件名的文件 * @return */ public static boolean downFile( String url, int port, String username, String password, String remotePath, String localPath, String fileName) { boolean success = false; FTPClient ftp = null; try { int reply; ftp = getConnection(url, port, username, password); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } boolean changeWorkDirState = false; changeWorkDirState = ftp.changeWorkingDirectory(remotePath); // 转移到FTP服务器目录 System.out.println(changeWorkDirState == true ? "切换FTP目录 成功" : "切换FTP目录 失败"); if (changeWorkDirState == false) return false; FTPFile[] fs = ftp.listFiles(); for (FTPFile ff : fs) { if (ff.getName().equals(fileName)) { File localFile = new File(localPath + "/" + ff.getName()); OutputStream is = new FileOutputStream(localFile); ftp.retrieveFile(ff.getName(), is); is.close(); } } ftp.logout(); success = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return success; }
/** * * * <pre> * <b>Description:</b> * Function remove folder from ftp * <b>Creation date: </b>02.05.08 * <b>Modification date: </b>02.05.08 * </pre> * * @param String sDirPath � removed directory * @author Vitalii Fedorets * @return boolean � true if success */ public boolean removeFolder(String sDirPath) throws Exception { try { File oDir = new File(sDirPath); FTPClient oFtp = this.initFtpClientLoginChangeWorkingDirectory(sDirPath); oFtp.changeWorkingDirectory(oDir.getParent().replace("\\", "/")); int iReply = oFtp.getReplyCode(); if (!FTPReply.isPositiveCompletion(iReply)) { log.setError("Not change work directory to `" + oDir.getParent().replace("\\", "/") + "`"); oFtp.disconnect(); return false; } if (!oFtp.removeDirectory(sDirPath)) { log.setError("Could not remove directory `" + sDirPath + "`"); oFtp.disconnect(); return false; } return true; } catch (Exception oEx) { throw oEx; } }
public void run() { try { FTPClient c = new FTPClient(); c.configure(ftpConfig); logger.debug("Trying to connect"); c.connect("127.0.0.1", 21211); logger.debug("Connected"); c.setSoTimeout(5000); if (!FTPReply.isPositiveCompletion(c.getReplyCode())) { logger.debug("Houston, we have a problem. D/C"); c.disconnect(); throw new Exception(); } if (c.login("drftpd", "drftpd")) { logger.debug("Logged-in, now waiting 5 secs and kill the thread."); _sc.addSuccess(); Thread.sleep(5000); c.disconnect(); } else { logger.debug("Login failed, D/C!"); throw new Exception(); } } catch (Exception e) { logger.debug(e, e); _sc.addFailure(); } logger.debug("exiting"); }
/** * Description: 向FTP服务器上传文件 * * @param host FTP服务器hostname * @param port FTP服务器端口 * @param username FTP登录账号 * @param password FTP登录密码 * @param basePath FTP服务器基础目录 * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath * @param filename 上传到FTP服务器上的文件名 * @param input 输入流 * @return 成功返回true,否则返回false */ public static boolean uploadFile( String host, int port, String username, String password, String basePath, String filePath, String filename, InputStream input) { boolean result = false; FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(host, port); // 连接FTP服务器 // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器 ftp.login(username, password); // 登录 reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return result; } // 切换到上传目录 if (!ftp.changeWorkingDirectory(basePath + filePath)) { // 如果目录不存在创建目录 String[] dirs = filePath.split("/"); String tempPath = basePath; for (String dir : dirs) { if (null == dir || "".equals(dir)) continue; tempPath += "/" + dir; if (!ftp.changeWorkingDirectory(tempPath)) { if (!ftp.makeDirectory(tempPath)) { return result; } else { ftp.changeWorkingDirectory(tempPath); } } } } // 设置上传文件的类型为二进制类型 ftp.setFileType(FTP.BINARY_FILE_TYPE); // 上传文件 if (!ftp.storeFile(filename, input)) { return result; } input.close(); ftp.logout(); result = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return result; }
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] args = null; String nomeArquivo = null; FTPClient ftp = new FTPClient(); try { ftp.connect("ftp.provedor.com.br"); // verifica se conectou com sucesso! if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { ftp.login("usuario", "senha"); } else { // erro ao se conectar ftp.disconnect(); System.out.println("Conex�o recusada"); System.exit(1); } ftp.changeWorkingDirectory("C:/Editorias/Futebol - CLASSIFICA��O"); // para cada arquivo informado... for (int i = 0; i < args.length; i++) { // abre um stream com o arquivo a ser enviado InputStream is = new FileInputStream(args[i]); // pega apenas o nome do arquivo int idx = args[i].lastIndexOf(File.separator); if (idx < 0) idx = 0; else idx++; nomeArquivo = args[i].substring(idx, args[i].length()); // ajusta o tipo do arquivo a ser enviado if (args[i].endsWith(".txt")) { ftp.setFileType(FTPClient.ASCII_FILE_TYPE); } else if (args[i].endsWith(".jpg")) { ftp.setFileType(FTPClient.BINARY_FILE_TYPE); } else { ftp.setFileType(FTPClient.ASCII_FILE_TYPE); } System.out.println("Enviando arquivo " + nomeArquivo + "..."); // faz o envio do arquivo ftp.storeFile(nomeArquivo, is); System.out.println("Arquivo " + nomeArquivo + " enviado com sucesso!"); } ftp.disconnect(); System.out.println("Fim. Tchau!"); } catch (Exception e) { System.out.println("Ocorreu um erro: " + e); System.exit(1); } }
public boolean test() { int base = 0; boolean error = false; FTPFile[] ftpFiles; testMsg = null; try { int reply; ftpClient.connect(ftpVO.getServer(), ftpVO.getPortasInteger()); // Check connection reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); testMsg = Resource.getString("ftpchooser.msg.noconnect"); return false; } // Login if (!ftpClient.login(ftpVO.getUser(), ftpVO.getPassword())) { ftpClient.logout(); testMsg = Resource.getString("ftpchooser.msg.nologin"); return false; } ftpClient.syst(); // Change directory if (!ftpClient.changeWorkingDirectory(ftpVO.getDirectory())) { testMsg = Resource.getString("ftpchooser.msg.nodirectory"); return false; } testMsg = Resource.getString("ftpchooser.msg.success"); ftpClient.logout(); } catch (IOException ex) { testMsg = ex.getLocalizedMessage(); error = true; } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException f) { } } } return !error; }
/** * @param remotePath 远程文件路径ַ ex:/upload/2012/xxxx.jpg * @param out 文件输出流 * @return */ public static boolean downFile(String remotePath, OutputStream out) { Boolean flag = Boolean.FALSE; // 得到文件名 ex: xxxx.jpg String fileName = getLastName(remotePath); // 得到文件存储路径 ex:/upload/2012 String remoteStorePath = getFilePath(remotePath); FTPClient ftpClient = null; try { ftpClient = getFTPClient(); // 得到返回答复码 int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { try { ftpClient.disconnect(); return flag; } catch (IOException e) { e.printStackTrace(); return flag; } } ftpClient.changeWorkingDirectory(remoteStorePath); // ftpClient.setFileType(FTP.BINARY_FILE_TYPE);// FTPFile[] fs = ftpClient.listFiles(); for (FTPFile file : fs) { if (fileName.equalsIgnoreCase(file.getName())) { flag = ftpClient.retrieveFile(fileName, out); break; } } ftpClient.logout(); } catch (IOException e) { e.printStackTrace(); } finally { if (null != ftpClient && ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException ioe) { } } } return flag; }
@Deprecated private FTPClient initFtpClientAndLogin() throws SocketException, IOException { if (oFtp != null) { return oFtp; } FTPClient oFtp = new FTPClient(); int iReply; oFtp.connect(_sFtpHost); iReply = oFtp.getReplyCode(); if (!FTPReply.isPositiveCompletion(iReply)) { log.setError("Could not connect to ftp host" + _sFtpHost); return null; } if (!oFtp.login(_sFtpUserName, _sFtpPassword)) { log.error( "Could not login with user `" + _sFtpUserName + "` and password `" + _sFtpPassword + "`"); oFtp.disconnect(); return null; } oFtp.enterLocalPassiveMode(); return oFtp; }
/** * * * <pre> * <b>Description:</b> * Function create ftp folder * <b>Creation date: </b>02.05.08 * <b>Modification date: </b>02.05.08 * </pre> * * @param String sDirName � directory name * @author Vitalii Fedorets * @return boolean � true if success */ public boolean createFolder(String sDirName) throws Exception { try { FTPClient oFtp = this.initFtpClientLoginChangeWorkingDirectory(sDirName); if (!oFtp.makeDirectory(sDirName)) { log.setError("Could not create directory `" + sDirName + "`"); oFtp.disconnect(); return false; } oFtp.disconnect(); return true; } catch (Exception oEx) { throw oEx; } }
private void logout() throws IOException { if (isConnected()) { ftpClient.logout(); ftpClient.disconnect(); setConnected(false); } }
/** * @param path ex:/upload/2023 * @param filename xxx.jpg * @param input 输入流 * @return */ public static boolean uploadFile(String path, String filename, InputStream input) { boolean success = false; FTPClient ftpClient = null; try { ftpClient = getFTPClient(); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { return success; } // 使用二进制上传 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpCreateDirectoryTree(ftpClient, path); success = ftpClient.storeFile(filename, input); input.close(); ftpClient.logout(); } catch (IOException e) { e.printStackTrace(); } finally { if (null != ftpClient && ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException ioe) { } } } return success; }
public static FTPClient getFTPClient() { FTPClient client = ftpClientThreadLocal.get(); if (client != null && client.isConnected()) { return client; } ftpClientThreadLocal.remove(); FTPClient ftpClient = new FTPClient(); // 创建ftpClient ftpClient.setControlEncoding("UTF-8"); // 设置字符编码 Boolean isConnect = connectFtp(ftpClient); ftpClient.enterLocalPassiveMode(); try { ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.setSoTimeout(1000 * 30); } catch (Exception e) { e.printStackTrace(); } // 得到返回答复码 int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } else { ftpClientThreadLocal.set(ftpClient); } return ftpClient; }
public static String downloadFromFTP(String url, String jarPath) { String[] splits = url.split("/"); String filename = splits[splits.length - 1]; FTPClient client = new FTPClient(); FileOutputStream fos = null; try { client.connect(host); client.login(username, passwd); // // The remote filename to be downloaded. // fos = new FileOutputStream(jarPath + "/" + filename); // // Download file from FTP server // client.retrieveFile(url, fos); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fos != null) { fos.close(); } client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } return filename; }
public Object makeObject() throws Exception { FTPClient client = new FTPClient(); try { if (uri.getPort() > 0) { client.connect(uri.getHost(), uri.getPort()); } else { client.connect(uri.getHost()); } if (!FTPReply.isPositiveCompletion(client.getReplyCode())) { throw new IOException("Ftp error: " + client.getReplyCode()); } if (!client.login(uri.getUsername(), uri.getPassword())) { throw new IOException("Ftp error: " + client.getReplyCode()); } if (!client.setFileType(FTP.BINARY_FILE_TYPE)) { throw new IOException("Ftp error. Couldn't set BINARY transfer type."); } } catch (Exception e) { if (client.isConnected()) { client.disconnect(); } throw e; } return client; }
/** * * * <pre> * <b>Description:</b> * Function connect to ftp and get attribute value from xml file by tag name * <b>Creation date: </b>02.07.2008 * <b>Modification date: </b>02.07.2008 * </pre> * * @param String sDirPath -- dirrectory where file located * @param String sFileName -- XML file name * @param String sTag -- searching tag in file * @param String sAttribute -- tag attribute * @author Oleksii Zozulenko. * @return String sAttrValue -- attribute value, or null if error * @exception Exception */ public String getXMLAttributeValue( String sDirPath, String sFileName, String sTag, String sAttribute) throws Exception { try { String sAttrValue = null; FTPClient oFtp = this.initFtpClientLoginChangeWorkingDirectory(sDirPath); ByteArrayOutputStream oBuf = new ByteArrayOutputStream(); if (!oFtp.retrieveFile(sFileName, oBuf)) { log.setError("Could not read file `" + sFileName + "`"); oFtp.disconnect(); return null; } oFtp.disconnect(); String sBuf = oBuf.toString(); oBuf.close(); if (!sBuf.contains(sTag)) { log.setError("File `" + sFileName + "` not contains tag `" + sTag + "`"); return null; } sBuf = sBuf.substring(sBuf.indexOf(sTag)); if (!sBuf.contains(sAttribute)) { log.setError( "File `" + sFileName + "` not contains tag `" + sTag + "` with attribute `" + sAttribute + "`"); return null; } sBuf = sBuf.substring(sBuf.indexOf(sAttribute + "=\"") + (sAttribute + "=\"").length()); sAttrValue = sBuf.substring(0, sBuf.indexOf("\"")); return sAttrValue; } catch (Exception oEx) { throw oEx; } }
/** * Description: 从FTP服务器下载文件 * * @param host FTP服务器hostname * @param port FTP服务器端口 * @param username FTP登录账号 * @param password FTP登录密码 * @param remotePath FTP服务器上的相对路径 * @param fileName 要下载的文件名 * @param localPath 下载后保存到本地的路径 * @return */ public static boolean downloadFile( String host, int port, String username, String password, String remotePath, String fileName, String localPath) { boolean result = false; FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(host, port); // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器 ftp.login(username, password); // 登录 reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return result; } ftp.changeWorkingDirectory(remotePath); // 转移到FTP服务器目录 FTPFile[] fs = ftp.listFiles(); for (FTPFile ff : fs) { if (ff.getName().equals(fileName)) { File localFile = new File(localPath + "/" + ff.getName()); OutputStream is = new FileOutputStream(localFile); ftp.retrieveFile(ff.getName(), is); is.close(); } } ftp.logout(); result = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return result; }
public boolean open() { boolean isSuccessful = false; if (isOpen) { throw new IllegalStateException("Is already open, must be closed before!"); } try { int reply; ftpClient.connect(ftpVO.getServer(), ftpVO.getPortasInteger()); reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); throw new IOException("Can't connect!"); } if (!ftpClient.login(ftpVO.getUser(), ftpVO.getPassword())) { ftpClient.logout(); throw new IOException("Can't login!"); } if (!ftpClient.changeWorkingDirectory(ftpVO.getDirectory())) { ftpClient.logout(); throw new IOException("Can't change directory!"); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); isSuccessful = true; } catch (Exception e) { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException f) { // do nothing } } isSuccessful = false; } isOpen = isSuccessful; return isSuccessful; }
public static void disConnectFtp(FTPClient ftpClient) { try { ftpClient.disconnect(); } catch (IOException e) { log.info("关闭连接失败!", e); e.printStackTrace(); } }
/** logout and disconnect */ public void close() { try { ftp.logout(); ftp.disconnect(); } catch (IOException e) { e.printStackTrace(); } }
private synchronized void closeFtpConnection() throws IOException { if (oFtp.isConnected()) { try { oFtp.logout(); } catch (org.apache.commons.net.ftp.FTPConnectionClosedException e) { } } oFtp.disconnect(); }
/** 서버와의 연결을 끊는다. */ public void disconnection() { try { client.logout(); if (client.isConnected()) { client.disconnect(); } } catch (IOException e) { e.printStackTrace(); } }
/** * * * <pre> * <b>Description:</b> * Function check exists directory on ftp * <b>Creation date: </b>02.05.08 * <b>Modification date: </b>02.05.08 * </pre> * * @param String String sDirPath � directory name in ftp * @author Vitalii Fedorets * @return boolean � true if success */ public boolean checkIfFolderExist(String sDirPath) throws Exception { try { FTPClient oFtp = this.initFtpClientLoginChangeWorkingDirectory(sDirPath); oFtp.disconnect(); return true; } catch (Exception oEx) { throw oEx; } }
@Override public void upload(UploadRequest uploadRequest) { ServerInfo serverInfo = uploadRequest.getServerInfo(); String host = serverInfo.getHost(); if (uploadRequest.isUseProxy()) { initializeProxy(host); } int attemptCount = 0; while (true) { try { login(serverInfo.getHost(), serverInfo.getLogin(), serverInfo.getPassword()); try { ftpClient.setSoTimeout(DEFAULT_SOCKET_TIMEOUT); } catch (SocketException e) { LOGGER.error("socket exception: {} {}", e.getMessage(), e.getStackTrace()); throw new RuntimeException("socket exception: " + e.getMessage()); } String prefixDirectory = serverInfo.getPrefix(); if (prefixDirectory != null) { ftpClient.changeWorkingDirectory(prefixDirectory); } File directory = new File(uploadRequest.getUploadDir()); uploadDir(directory); ftpClient.logout(); break; } catch (IOException e) { LOGGER.error("i/o error: {}, retrying", e.getMessage()); attemptCount++; if (attemptCount > 5) { LOGGER.debug("choosing another proxy after 5 attempts"); initializeProxy(host); attemptCount = 0; } } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException ioe) { // do nothing } } } } }
/** * Description: 从FTP服务器下载单个文件 * * @param url FTP服务器hostname * @param port FTP服务器端口 * @param username FTP登录账号 * @param password FTP登录密码 * @param remotePath FTP服务器上的相对路径+文件名 example:/imagename.jpg * @param localPath 下载后保存到本地的路径 * @param fileName 保存为该文件名的文件 * @return */ public static boolean downSingleFile( String url, int port, String username, String password, String remotePath, String localPath, String fileName) { boolean success = false; FTPClient ftp = null; FileOutputStream fos = null; try { int reply; ftp = getConnection(url, port, username, password); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } boolean changeWorkDirState = false; fos = new FileOutputStream(localPath + "/" + fileName); ftp.setBufferSize(1024); // 设置文件类型(二进制) ftp.setFileType(FTPClient.BINARY_FILE_TYPE); ftp.retrieveFile(remotePath, fos); changeWorkDirState = ftp.changeWorkingDirectory(remotePath); // 转移到FTP服务器目录 ftp.logout(); success = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return success; }
public void close() { try { if (ftp != null) { ftp.logout(); ftp.disconnect(); } } catch (Exception ex) { logger.info("\\== ERROR WHILE EXECUTE FTP ==// quit error"); } ftp = null; }
/** * Logout and disconnect the given FTPClient. * * * @param client * @throws IOException */ private void disconnect(FTPClient client) throws IOException { if (client != null) { if (!client.isConnected()) { throw new FTPException("Client not connected"); } boolean logoutSuccess = client.logout(); client.disconnect(); if (!logoutSuccess) { LOG.warn("Logout failed while disconnecting, error code - " + client.getReplyCode()); } } }
public void connectFtp() throws Exception { ftp.setDefaultTimeout(1500); ftp.connect(hcs.getAddress()); ftp.login(hcs.getUsername(), hcs.getPassword()); int reply = ftp.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { System.out.println("HCS " + hcs.getLabel() + ": Connected successfully"); } else { System.out.println("HCS " + hcs.getLabel() + ": Connection failed"); ftp.disconnect(); } }
public void close() { if (!isOpen) { throw new IllegalStateException("Is already closed, must be opened before!"); } else { try { ftpClient.logout(); ftpClient.disconnect(); } catch (Exception e) { // do nothing } isOpen = false; } }
/** * Disconnects. * * @throws FtpException */ public void disconnect() throws FtpException { if (ftp == null) { throw new FtpException(NOT_CONNECTED); } try { ftp.logout(); ftp.disconnect(); } catch (IOException e) { throw new FtpException(e); } finally { ftp = null; } }
/** * * * <pre> * <b>Description:</b> * Function check file content on ftp folder * <b>Creation date: </b>02.05.08 * <b>Modification date: </b>02.05.08 * </pre> * * @param String sDirPath � directory contains file * @param String sFileName � file name * @param String sText - text which contains in file * @author Vitalii Fedorets * @return boolean � true if file contains text */ public boolean checkTextInFile(String sDirPath, String sFileName, String sText) throws Exception { try { FTPClient oFtp = this.initFtpClientLoginChangeWorkingDirectory(sDirPath); ByteArrayOutputStream oBuf = new ByteArrayOutputStream(); if (!oFtp.retrieveFile(sFileName, oBuf)) { log.setError("Could not read file `" + sFileName + "`"); oFtp.disconnect(); return false; } oFtp.disconnect(); String sBuf = oBuf.toString(); oBuf.close(); return sBuf.contains(sText); } catch (Exception oEx) { throw oEx; } }