/** * 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; }
public File getRemoteFileFromREM(String filename) { File localFile = new File(filename); Boolean isDownloaded = false; try { // Connection ftpsClient.connect(this.ftpServerAdress, FTP_PORT); ftpsClient.setBufferSize(1024 * 1024); ftpsClient.setConnectTimeout(1000000); ftpsClient.setSoTimeout(1000000); // Commands printed ftpsClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); // Connection with host is established and user is logged into if (FTPReply.isPositiveCompletion(ftpsClient.getReplyCode())) { if (ftpsClient.login(this.ftpUsername, this.ftpPassword)) { // Connection is secured, other wise certificat must be accepted ftpsClient.execPBSZ(0); ftpsClient.execPROT("P"); ftpsClient.setFileType(FTP.BINARY_FILE_TYPE); ftpsClient.enterLocalPassiveMode(); ftpsClient.changeWorkingDirectory("/"); isDownloaded = ftpsClient.retrieveFile(filename, new FileOutputStream(localFile)); // Disconnect ftpsClient.logout(); ftpsClient.disconnect(); } else { System.out.println("FTP login failed"); } } else { System.out.println("FTP connect to host failed"); } } catch (IOException ex) { Logger.getLogger(FTPSConnection.class.getName()).log(Level.SEVERE, null, ex); } if (!isDownloaded) localFile = null; return localFile; }
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; }
/** * @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; }
/** * Opens a new connection and performs login with user name and password if set. * * @throws IOException */ protected void connectAndLogin() throws IOException { if (!ftpClient.isConnected()) { ftpClient.connect(getEndpointConfiguration().getHost(), getEndpointConfiguration().getPort()); log.info("Connected to FTP server: " + ftpClient.getReplyString()); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new CitrusRuntimeException("FTP server refused connection."); } log.info("Successfully opened connection to FTP server"); if (getEndpointConfiguration().getUser() != null) { log.info(String.format("Login as user: '******'", getEndpointConfiguration().getUser())); boolean login = ftpClient.login( getEndpointConfiguration().getUser(), getEndpointConfiguration().getPassword()); if (!login) { throw new CitrusRuntimeException( String.format( "Failed to login to FTP server using credentials: %s:%s", getEndpointConfiguration().getUser(), getEndpointConfiguration().getPassword())); } } } }
@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; }
@Override public PropertyList executeCallback(Metadata metadata, PropertyList properties) throws FTPException { try { int port = getPort(metadata.getPropertyList()); String servername = getServername(metadata.getPropertyList()); info("Connecting to FTP-Server: " + servername + ":" + port); start(); getFTPClient().connect(servername, port); int reply = getFTPClient().getReplyCode(); stop(); if (!FTPReply.isPositiveCompletion(reply)) { getFTPClient().disconnect(); throw new FTPException("FTP server refused connection"); } return null; } catch (SocketException ex) { setException(ex); throw new FTPCommunicationException("Could not connect to FTP-Server", ex); } catch (IOException ex) { setException(ex); throw new FTPCommunicationException("Could not connect to FTP-Server", ex); } }
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"); }
private FTPFile[] listFilesInDirectory(String relPath) throws IOException { FTPFile[] files; // VFS-307: no check if we can simply list the files, this might fail if there are spaces in the // path files = getFtpClient().listFiles(relPath); if (FTPReply.isPositiveCompletion(getFtpClient().getReplyCode())) { return files; } // VFS-307: now try the hard way by cd'ing into the directory, list and cd back // if VFS is required to fallback here the user might experience a real bad FTP performance // as then every list requires 4 ftp commands. String workingDirectory = null; if (relPath != null) { workingDirectory = getFtpClient().printWorkingDirectory(); if (!getFtpClient().changeWorkingDirectory(relPath)) { return null; } } files = getFtpClient().listFiles(); if (relPath != null && !getFtpClient().changeWorkingDirectory(workingDirectory)) { throw new FileSystemException( "vfs.provider.ftp.wrapper/change-work-directory-back.error", workingDirectory); } return files; }
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; }
/** * * * <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; } }
/** * 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 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 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; }
@Override public void send(Message message, TestContext context) { FtpMessage ftpMessage; if (message instanceof FtpMessage) { ftpMessage = (FtpMessage) message; } else { ftpMessage = new FtpMessage(message); } String correlationKeyName = getEndpointConfiguration().getCorrelator().getCorrelationKeyName(getName()); String correlationKey = getEndpointConfiguration().getCorrelator().getCorrelationKey(ftpMessage); correlationManager.saveCorrelationKey(correlationKeyName, correlationKey, context); log.info( String.format( "Sending FTP message to: ftp://'%s:%s'", getEndpointConfiguration().getHost(), getEndpointConfiguration().getPort())); if (log.isDebugEnabled()) { log.debug("Message to be sent:\n" + ftpMessage.getPayload().toString()); } try { connectAndLogin(); int reply = ftpClient.sendCommand(ftpMessage.getCommand(), ftpMessage.getArguments()); if (!FTPReply.isPositiveCompletion(reply) && !FTPReply.isPositivePreliminary(reply)) { throw new CitrusRuntimeException( String.format( "Failed to send FTP command - reply is: %s:%s", reply, ftpClient.getReplyString())); } log.info( String.format( "FTP message was successfully sent to: '%s:%s'", getEndpointConfiguration().getHost(), getEndpointConfiguration().getPort())); correlationManager.store( correlationKey, new FtpMessage(ftpMessage.getCommand(), ftpMessage.getArguments()) .replyCode(reply) .replyString(ftpClient.getReplyString())); } catch (IOException e) { throw new CitrusRuntimeException("Failed to execute ftp command", e); } }
public static boolean mkdir(FTPClient ftp, String path) throws IOException { String[] pathNames = path.split("/"); ftp.changeWorkingDirectory("/"); for (int i = 0; i < pathNames.length; i++) { if (!ftp.changeWorkingDirectory(pathNames[i])) { if (FTPReply.isPositiveCompletion(ftp.mkd(pathNames[i]))) { ftp.changeWorkingDirectory(pathNames[i]); } else { FTPLogger.error("Make dir failed with path: " + pathNames[i]); return false; } } } return true; }
private void connect() throws SocketException, IOException { // send the command.. ftpClient.connect(host, hostPort); // check reply code... int replyCode = ftpClient.getReplyCode(); boolean sucess = FTPReply.isPositiveCompletion(replyCode); // sucess? if (!sucess) { ftpClient.disconnect(); throw new IOException("FTP server refused connection."); } setConnected(sucess); }
@Override public void connect() { LOGGER.info("Connecting to " + username() + "@" + host() + ":" + String.valueOf(port())); reconnect = true; try { ftpClient.connect(host(), port()); } catch (IOException e) { throw new VirtualFileException(e); } if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { disconnect(); return; } login(); setFileType(FTP.BINARY_FILE_TYPE); }
/** * 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; }
private void login(String host, String login, String password) throws IOException { ftpClient.connect(host); ftpClient.login(login, password); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); LOGGER.error( "ftp server {} refused connection, reply string: {}", host, ftpClient.getReplyString()); throw new RuntimeException("ftp server " + host + " refused connection"); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Connected to {}, reply string: {}", host, ftpClient.getReplyString()); } }
/** * @param sDirPath * @return * @throws SocketException * @throws IOException */ private FTPClient initFtpClientLoginChangeWorkingDirectory(String sDirPath) throws SocketException, IOException { if (oFtp != null) { return oFtp; } oFtp = initFtpClientAndLogin(); int iReply; oFtp.changeWorkingDirectory(sDirPath); iReply = oFtp.getReplyCode(); if (!FTPReply.isPositiveCompletion(iReply)) { log.setError("Not change work directory to `" + sDirPath + "`"); oFtp.disconnect(); return null; } return oFtp; }
/** * Connect to ftp server * * @param server the host you connect * @param user the user account to login [anonymous as default] * @param passwd the password according to you account, and if the account is anonymous "" as * default */ public void initConnection(String server, String user, String passwd) { ftp = new FTPClient(); try { ftp.connect(server); ftp.login(user, passwd); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); LogUtils.log("disconnect after login"); } LogUtils.log("Connected to " + server + " with name [" + user + "]"); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public static void main(String[] args) { String server = "localhost"; int port = 16885; String user = "******"; String pass = "******"; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); showServerReply(ftpClient); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { System.out.println("Operation failed. Server reply code: " + replyCode); return; } boolean success = ftpClient.login(user, pass); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); showServerReply(ftpClient); if (!success) { System.out.println("Could not login to the server"); return; } else { System.out.println("LOGGED IN SERVER"); ftpClient.changeWorkingDirectory("C:\\Users\\Dileep\\Desktop\\temp"); // File outFile = new File("C:\\Users\\Dileep\\Desktop\\temp\\newFolder","NewFile.txt"); ftpClient.enterLocalPassiveMode(); // FileOutputStream outputStream = new FileOutputStream(outFile); InputStream fileInputStream = ftpClient.retrieveFileStream("Dileep.txt"); manipulateFile(fileInputStream); /*if (ftpClient.retrieveFile("Dileep.txt", outputStream)){ outputStream.close(); }*/ } ftpClient.logout(); } catch (IOException ex) { System.out.println("Oops! Something wrong happened"); ex.printStackTrace(); } finally { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
private FTPClient connect() throws FTPException { try { FTPClient ftp = new FTPClient(); ftp.connect(host, port); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); } ftp.login(userName, password); ftp.setFileType(FTP.BINARY_FILE_TYPE); return ftp; } catch (SocketException e) { throw new FTPException("Failed to connect to server", e); } catch (IOException e) { throw new FTPException("Failed to connect to server", e); } }
/** * 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 static Boolean connectFtp(FTPClient ftpClient) { Boolean isConnect = Boolean.FALSE; try { ftpClient.connect(ftpServer, Integer.parseInt(ftpPort)); // 连接后检测返回码来校验连接是否成功 int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { // 登陆到ftp服务器 if (ftpClient.login(ftpUsername, ftpPassword)) { ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); return true; } } else { ftpClient.disconnect(); } } catch (IOException e) { e.printStackTrace(); } return isConnect; }
/** * @param filePath 文件的完整存储路径 ex:/upload/photo_image/xxxx.jpg * @return */ public static Boolean delFtpFile(String filePath) { Boolean success = Boolean.FALSE; FTPClient ftpClient = getFTPClient(); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { return success; } try { success = ftpClient.deleteFile(filePath); } catch (IOException e) { e.printStackTrace(); } finally { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } return success; }