private void connectFtpServer() { try { ftpClient = new FTPClient(); FTPClientConfig ftpClientConfig = new FTPClientConfig(); ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID()); ftpClient.configure(ftpClientConfig); URL url = getURL(); if (url.getPort() <= 0) { ftpClient.connect(url.getHost()); } else { ftpClient.connect(url.getHost(), url.getPort()); } if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { throw new VFSRuntimeException("连接失败!"); } if (url.getUserInfo() != null) { String userInfo[] = url.getUserInfo().split(":"); String userName = null; String password = null; if (userInfo.length >= 1) { userName = userInfo[0]; } if (userInfo.length >= 2) { password = userInfo[1]; } if (!ftpClient.login(userName, password)) { throw new VFSRuntimeException("登录失败:" + url.toString()); } if (!ftpClient.setFileType(FTP.BINARY_FILE_TYPE)) { throw new VFSRuntimeException("设置二进制类型失败"); } ftpClient.setBufferSize(BUF_SIZE); ftpClient.setControlEncoding("utf-8"); } } catch (Exception e) { throw new VFSRuntimeException(e); } }
private void login() throws IOException { if (!isConnected()) { connect(); } ftpClient.login(user, password); if (passiveMode) { ftpClient.enterLocalPassiveMode(); } // PDF transmitted with ASCII file type break the file ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.setBufferSize(0); ftpClient.setControlKeepAliveTimeout(timeOutInSeconds); }
/** * 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; }
/** * Connect to the FTP server using configuration parameters * * * @return An FTPClient instance * @throws IOException */ private FTPClient connect() throws IOException { FTPClient client = null; Configuration conf = getConf(); String host = conf.get("fs.ftp.host"); int port = conf.getInt("fs.ftp.host.port", FTP.DEFAULT_PORT); String user = conf.get("fs.ftp.user." + host); String password = conf.get("fs.ftp.password." + host); client = new FTPClient(); client.connect(host, port); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("Server - " + host + " refused connection on port - " + port); } else if (client.login(user, password)) { client.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE); client.setFileType(FTP.BINARY_FILE_TYPE); client.setBufferSize(DEFAULT_BUFFER_SIZE); } else { throw new IOException("Login failed on server - " + host + ", port - " + port); } return client; }
public boolean ftpDownload() { boolean status = false; final String username = "******"; final String password = "******"; final String hostname = "ftp.memelab.ca"; final int port = 21; String SFTPWORKINGDIR = "/public_html/jessescott/storage/android"; FTPClient ftp = new FTPClient(); try { ftp.connect(hostname, port); ftp.login(username, password); ftp.changeWorkingDirectory(SFTPWORKINGDIR); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.setBufferSize(1024); ftp.enterLocalPassiveMode(); OutputStream output = null; FTPFile[] files = ftp.listFiles(); // Set Log Directory & File File logFile = new File(LOG_DIRECTORY + "logfile.txt"); Log.d("FTP", "LOG should exist at " + logFile.getAbsolutePath()); if (!logFile.exists()) { try { logFile.createNewFile(); } catch (Exception e) { e.printStackTrace(); } } for (FTPFile f : files) { // Log Names Log.d("FTP", f.toFormattedString()); // Set Path String remoteFile = f.getName(); Log.d("FTP", "REMOTE file " + remoteFile); String localFile = MEDIA_DIRECTORY; localFile += remoteFile; Log.d("FTP", " is being put in LOCAL path " + localFile); output = new BufferedOutputStream(new FileOutputStream(localFile)); // Set Time Time now = new Time(Time.getCurrentTimezone()); now.setToNow(); // Set Logger BufferedWriter logger = new BufferedWriter(new FileWriter(logFile, true)); logger.append("Download for " + localFile + " started at " + now.format("%k:%M:%S")); logger.newLine(); Long startTime = System.currentTimeMillis(); // HTTP System.setProperty("http.keepAlive", "false"); // Get Files Boolean success = ftp.retrieveFile(remoteFile, output); status = success; if (success) { Log.d("FTP", "SUCCESS"); now.setToNow(); Long elapsedTime = (System.currentTimeMillis() - startTime) / 1000; logger.append("Download for " + localFile + " finished at " + now.format("%k:%M:%S")); logger.newLine(); logger.append("for an elapsedTime of " + elapsedTime + " seconds"); logger.newLine(); logger.newLine(); } // Close Logger logger.flush(); logger.close(); // Close Buffer if (ftp != null) { output.close(); } } ftp.logout(); ftp.disconnect(); } catch (Exception e) { e.printStackTrace(); } return status; }