private static void ftpCreateDirectoryTree(FTPClient client, String dirTree) throws IOException { boolean dirExists = true; // tokenize the string and attempt to change into each directory level. // If you cannot, then start creating. String[] directories = dirTree.split("/"); for (String dir : directories) { if (!dir.isEmpty()) { if (dirExists) { dirExists = client.changeWorkingDirectory(dir); } if (!dirExists) { if (!client.makeDirectory(dir)) { throw new IOException( "Unable to create remote directory '" + dir + "'. error='" + client.getReplyString() + "'"); } if (!client.changeWorkingDirectory(dir)) { throw new IOException( "Unable to change into newly created remote directory '" + dir + "'. error='" + client.getReplyString() + "'"); } } } } }
@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); } }
/** * Function retrieved file on the remote server NOTE: This function closes output stream after * retrieving file content * * @param fileName * @param fileOutput * @return * @throws SocketException * @throws IOException */ public boolean retrieveFile(String fileName, OutputStream fileOutput) throws SocketException, IOException { boolean fileRetrieved = false; connect2Server(); if (oFtp.isConnected()) { try { fileRetrieved = oFtp.retrieveFile(fileName, fileOutput); if (fileRetrieved) { logMessage("File '" + fileName + "' retrieved"); } else { logError( "Can't retrieve file " + fileName + " FTP reply code: " + oFtp.getReplyCode() + " Ftp message: " + oFtp.getReplyString()); } fileOutput.close(); } catch (IOException ioe) { log.warning("FTPUtil - retrieveFile(): " + ioe.toString()); return false; } } this.closeFtpConnection(); return fileRetrieved; }
/** * 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())); } } } }
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()); } }
private static void ftpStuff() { try { FTPClient ftp = new FTPClient(); ftp.connect("ftp.ncbi.nih.gov"); System.out.println(ftp.getReplyString()); ftp.login("anonymous", "*****@*****.**"); System.out.println("before list files..."); // ftp.li FTPFile[] files = ftp.listFiles(BASE_FOLDER); System.out.println(files.length); for (FTPFile file : files) { if (file.getName().endsWith(".gbff.gz")) { StringWriter writer = null; String charset = "ASCII"; GZIPInputStream inputStream = new GZIPInputStream(ftp.retrieveFileStream(BASE_FOLDER + "/" + file.getName())); System.out.println("ftp.getControlEncoding() = " + ftp.getControlEncoding()); Reader decoder = new InputStreamReader(inputStream, charset); BufferedReader buffered = new BufferedReader(decoder); String line = null; while ((line = buffered.readLine()) != null) { System.out.println("line = " + line); } System.exit(0); } } } catch (Exception ex) { Logger.getLogger(ImportGenBank.class.getName()).log(Level.SEVERE, null, ex); } }
/** * Uploads a local file to the FTP server. * * @param remote Name of the remote file * @param local Local InputStream * @param isBinaryFile Indication iff the file is binary * @throws FtpException */ public void upload(String remote, InputStream local, boolean isBinaryFile) throws FtpException { if (ftp == null) { throw new FtpException(NOT_CONNECTED); } try { if (isBinaryFile) { ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); } boolean ok = ftp.storeFile(remote, local); if (!ok) { String msg = ftp.getReplyString(); throw new FtpException(msg); } local.close(); } catch (FileNotFoundException fnfe) { throw new FtpException(fnfe); } catch (IOException ioe) { throw new FtpException(ioe); } }
public static void main(String[] args) throws IOException { OLAFile olaFile = new OLAFile( 19, 56, 51, "1111333355557777", "P161486", "M", "AG", "Nanninga", "Testweg", "12", "9439 HW", "Achterwoude", "987654", "Flipje Betuwe"); String server = "192.168.55.2"; FTPClient ftp = new FTPClient(); ftp.connect(server); ftp.enterLocalPassiveMode(); ftp.setFileType(FTP.BINARY_FILE_TYPE); System.out.println("Connected to " + server + "."); System.out.print(ftp.getReplyString()); InputStream inputStream = olaFile.getInputStream(); System.out.println("uploading file"); boolean done = ftp.storeFile("input/" + olaFile.getRef() + ".ola", inputStream); inputStream.close(); if (done) { System.out.println("uploaded file"); } else { System.out.println("upload failed"); } }
private synchronized void connect2Server() throws SocketException, IOException { if (oFtp == null) { this.oFtp = new FTPClient(); } if (log != null) { if (LogLevel.getValue(log.getLogLevel()).ordinal() > LogLevel.DEBUG.ordinal()) { oFtp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.err))); } } if (_port == 0) { oFtp.connect(this._sFtpHost, 21); } else { oFtp.connect(this._sFtpHost, _port); } if (!oFtp.login(this._sFtpUserName, this._sFtpPassword)) { logError("Can't login to server. FTP responce: " + oFtp.getReplyString()); } oFtp.enterLocalPassiveMode(); }
public void test01LoginFailed() { try (final Tx tx = StructrApp.getInstance(securityContext).tx()) { FTPClient ftp = new FTPClient(); ftp.connect("127.0.0.1", ftpPort); logger.log(Level.INFO, "Reply from FTP server:", ftp.getReplyString()); int reply = ftp.getReplyCode(); assertTrue(FTPReply.isPositiveCompletion(reply)); boolean loginSuccess = ftp.login("jt978hasdl", "lj3498ha"); logger.log(Level.INFO, "Try to login as jt978hasdl/lj3498ha:", loginSuccess); assertFalse(loginSuccess); ftp.disconnect(); } catch (IOException | FrameworkException ex) { logger.log(Level.SEVERE, "Error in FTP test", ex); fail("Unexpected exception: " + ex.getMessage()); } }
public static Map<String, Object> putFile(DispatchContext dctx, Map<String, ?> context) { Locale locale = (Locale) context.get("locale"); Debug.logInfo("[putFile] starting...", module); InputStream localFile = null; try { localFile = new FileInputStream((String) context.get("localFilename")); } catch (IOException ioe) { Debug.logError(ioe, "[putFile] Problem opening local file", module); return ServiceUtil.returnError( UtilProperties.getMessage(resource, "CommonFtpFileCannotBeOpen", locale)); } List<String> errorList = new LinkedList<String>(); FTPClient ftp = new FTPClient(); try { Integer defaultTimeout = (Integer) context.get("defaultTimeout"); if (UtilValidate.isNotEmpty(defaultTimeout)) { Debug.logInfo( "[putFile] set default timeout to: " + defaultTimeout.intValue() + " milliseconds", module); ftp.setDefaultTimeout(defaultTimeout.intValue()); } Debug.logInfo("[putFile] connecting to: " + (String) context.get("hostname"), module); ftp.connect((String) context.get("hostname")); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { Debug.logInfo("[putFile] Server refused connection", module); errorList.add(UtilProperties.getMessage(resource, "CommonFtpConnectionRefused", locale)); } else { String username = (String) context.get("username"); String password = (String) context.get("password"); Debug.logInfo( "[putFile] logging in: username="******", password="******"[putFile] login failed", module); errorList.add( UtilProperties.getMessage( resource, "CommonFtpLoginFailure", UtilMisc.toMap("username", username, "password", password), locale)); } else { Boolean binaryTransfer = (Boolean) context.get("binaryTransfer"); boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue(); if (binary) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } Boolean passiveMode = (Boolean) context.get("passiveMode"); boolean passive = (passiveMode == null) ? true : passiveMode.booleanValue(); if (passive) { ftp.enterLocalPassiveMode(); } Debug.logInfo( "[putFile] storing local file remotely as: " + context.get("remoteFilename"), module); if (!ftp.storeFile((String) context.get("remoteFilename"), localFile)) { Debug.logInfo("[putFile] store was unsuccessful", module); errorList.add( UtilProperties.getMessage( resource, "CommonFtpFileNotSentSuccesfully", UtilMisc.toMap("replyString", ftp.getReplyString()), locale)); } else { Debug.logInfo("[putFile] store was successful", module); List<String> siteCommands = checkList(context.get("siteCommands"), String.class); if (siteCommands != null) { for (String command : siteCommands) { Debug.logInfo("[putFile] sending SITE command: " + command, module); if (!ftp.sendSiteCommand(command)) { errorList.add( UtilProperties.getMessage( resource, "CommonFtpSiteCommandFailed", UtilMisc.toMap("command", command, "replyString", ftp.getReplyString()), locale)); } } } } } ftp.logout(); } } catch (IOException ioe) { Debug.logWarning(ioe, "[putFile] caught exception: " + ioe.getMessage(), module); errorList.add( UtilProperties.getMessage( resource, "CommonFtpProblemWithTransfer", UtilMisc.toMap("errorString", ioe.getMessage()), locale)); } finally { try { if (ftp.isConnected()) { ftp.disconnect(); } } catch (Exception e) { Debug.logWarning(e, "[putFile] Problem with FTP disconnect: ", module); } try { localFile.close(); } catch (Exception e) { Debug.logWarning(e, "[putFile] Problem closing local file: ", module); } } if (errorList.size() > 0) { Debug.logError( "[putFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList, module); return ServiceUtil.returnError(errorList); } Debug.logInfo("[putFile] finished successfully", module); return ServiceUtil.returnSuccess(); }
protected void process() { String actPath = getParameter("actPath"); if ((actPath == null) || (actPath.trim().length() == 0)) { actPath = getCwd(); } if (!this.checkAccess(actPath)) { return; } String ftpServerName = getParameter("ftpServerName"); if (ftpServerName == null) { ftpParamForm(null); return; } StringBuffer alertText = new StringBuffer(); if (ftpServerName.trim().length() == 0) { alertText.append( getResource("alert.missingFtpServer", "FTP Server is a required field") + "\\n"); } String userid = getParameter("userid"); if (userid.trim().length() == 0) { alertText.append(getResource("alert.missingFtpUserid", "Userid is a required field") + "\\n"); } String password = getParameter("password"); if (password.trim().length() == 0) { alertText.append( getResource("alert.missingFtpPassword", "Password is a required field") + "\\n"); } String remoteDir = getParameter("remoteDir"); if (alertText.length() > 0) { ftpParamForm(alertText.toString()); return; } output.println("<HTML>"); output.println("<HEAD>"); output.println( "<link rel=\"stylesheet\" type=\"text/css\" href=\"/webfilesys/styles/common.css\">"); output.println( "<link rel=\"stylesheet\" type=\"text/css\" href=\"/webfilesys/styles/skins/" + userMgr.getCSS(uid) + ".css\">"); output.println("</HEAD>"); output.println("<BODY>"); headLine(getResource("label.ftpBackupHead", "Backup to FTP Server")); output.println("<br>"); output.println("<form accept-charset=\"utf-8\" name=\"form1\">"); output.println("<table class=\"dataForm\" width=\"100%\">"); output.println("<tr><td class=\"formParm1\">"); output.println(getResource("label.ftpServerName", "Name or IP of FTP server") + ":"); output.println("</td>"); output.println("<td class=\"formParm2\">"); output.println(ftpServerName); output.println("</td></tr>"); output.println("<tr><td colspan=\"2\" class=\"formParm1\">"); output.println(getResource("label.ftpLocalDir", "Local Folder to backup") + ":"); output.println("</td></tr>"); output.println("<tr><td colspan=\"2\" class=\"formParm2\">"); output.println(CommonUtils.shortName(getHeadlinePath(actPath), 70)); output.println("</td></tr>"); output.println("<tr><td colspan=\"2\" class=\"formParm1\">"); output.println(getResource("label.currentcopy", "current file") + ":"); output.println("</td></tr>"); output.println("<tr><td colspan=\"2\" class=\"formParm2\">"); output.println("<span id=\"currentFile\"/>"); output.println("</td></tr>"); output.println("<tr><td colspan=\"2\" class=\"formParm1\">"); output.println(getResource("label.xferStatus", "transferred") + ":"); output.println("</td></tr>"); output.println("<tr><td colspan=\"2\" class=\"formParm2\">"); output.println("<span id=\"xferStatus\"/>"); output.println("</td></tr>"); output.println("</table>"); output.println("</form>"); String subDir = null; int lastSepIdx = actPath.lastIndexOf(File.separator); if ((lastSepIdx >= 0) && (lastSepIdx < (actPath.length() - 1))) { subDir = actPath.substring(lastSepIdx + 1); } boolean recursive = (getParameter("recursive") != null); FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(ftpServerName); Logger.getLogger(getClass()) .debug("FTP connect to " + ftpServerName + " response: " + ftpClient.getReplyString()); int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { if (ftpClient.login(userid, password)) { ftpClient.setFileType(FTP.IMAGE_FILE_TYPE); if ((remoteDir.trim().length() > 0) && (!ftpClient.changeWorkingDirectory(remoteDir))) { javascriptAlert("FTP remote directory " + remoteDir + " does not exist!"); } else { boolean remoteChdirOk = true; if (!ftpClient.changeWorkingDirectory(subDir)) { if (!ftpClient.makeDirectory(subDir)) { Logger.getLogger(getClass()).warn("FTP cannot create remote directory " + subDir); remoteChdirOk = false; } else { Logger.getLogger(getClass()).debug("FTP created new remote directory " + subDir); if (!ftpClient.changeWorkingDirectory(subDir)) { Logger.getLogger(getClass()) .warn("FTP cannot chdir to remote directory " + subDir); remoteChdirOk = false; } } } if (remoteChdirOk) { if (!backupDir(ftpClient, actPath, recursive, output)) { javascriptAlert("FTP backup failed"); } else { output.println("<script language=\"javascript\">"); output.println("document.getElementById('currentFile').innerHTML='';"); output.println("</script>"); } } else { javascriptAlert("FTP cannot create remote subdirectory " + subDir); } } } else { Logger.getLogger(getClass()).info("FTP connect to " + ftpServerName + " login failed"); javascriptAlert("Login to FTP server " + ftpServerName + " failed"); } } else { Logger.getLogger(getClass()) .warn("FTP connect to " + ftpServerName + " response: " + reply); javascriptAlert("Login to FTP server " + ftpServerName + " failed"); } ftpClient.logout(); ftpClient.disconnect(); // output.println("<br>" + filesTransferred + " files (" + bytesTransferred / 1024 + " KB) // transferred"); } catch (SocketException sockEx) { Logger.getLogger(getClass()).warn(sockEx); javascriptAlert("FTP transfer failed: " + sockEx); } catch (IOException ioEx) { Logger.getLogger(getClass()).warn(ioEx); javascriptAlert("FTP transfer failed: " + ioEx); } output.println( "<center><FORM><INPUT type=\"Button\" VALUE=\"" + getResource("button.closewin", "Close Window") + "\" onClick=\"self.close()\"></FORM></center>"); output.flush(); }
@Override public Future<Set<File>> download(LayerRequest currentLayer) throws Exception { this.currentLayer = currentLayer; currentLayer.setMetadata(this.includesMetadata()); File directory = getDirectory(); Set<File> fileSet = new HashSet<File>(); List<String> urls = this.getUrls(currentLayer); for (String url : urls) { InputStream inputStream = null; URL currentURL = new URL(url); String ftpServerAddress = currentURL.getHost(); String currentPath = currentURL.getPath(); FTPClient ftp = new FTPClient(); int delimiterIndex = currentPath.lastIndexOf("/"); String remoteDirectory = currentPath.substring(0, delimiterIndex); String fileName = currentPath.substring(delimiterIndex + 1); try { int reply; ftp.connect(ftpServerAddress); // Although they are open FTP servers, in order to access the files, a anonymous login is // necessary. ftp.login("anonymous", "anonymous"); System.out.println("Connected to " + ftpServerAddress + "."); System.out.print(ftp.getReplyString()); // After connection attempt, you should check the reply code to verify success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } reply = ftp.getReplyCode(); // enter passive mode ftp.enterLocalPassiveMode(); // change current directory ftp.changeWorkingDirectory(remoteDirectory); // check if the file with given name exists in ftp server try { FTPFile[] ftpFiles = ftp.listFiles(fileName); if (ftpFiles != null && ftpFiles.length > 0) { for (FTPFile file : ftpFiles) { if (!file.isFile()) continue; System.out.println("Found file:" + file.getName()); // transfer the file inputStream = ftp.retrieveFileStream(file.getName()); // save the file and add to fileset // TODO: ftp file does not contain MIME type. File outputFile = OgpFileUtils.createNewFileFromDownload(fileName, "ZIP", directory); // FileUtils with a BufferedInputStream seems to be the fastest method with a small // sample size. requires more testing BufferedInputStream bufferedIn = null; try { bufferedIn = new BufferedInputStream(inputStream); FileUtils.copyInputStreamToFile(bufferedIn, outputFile); fileSet.add(outputFile); } finally { IOUtils.closeQuietly(bufferedIn); } } } } catch (IOException e) { e.printStackTrace(); } finally { ftp.logout(); } } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } IOUtils.closeQuietly(inputStream); } } return new AsyncResult<Set<File>>(fileSet); };
/** * The method that handles file uploading, this method takes the absolute file path of a local * file to be uploaded to the remote FTP server, and the remote file will then be transfered to * the FTP server and saved as the relative path name specified in method setRemoteFile * * @param localfilename – the local absolute file name of the file in local hard drive that needs * to FTP over */ public synchronized boolean uploadFile(String localfilename, String remoteFile) { final BufferedInputStream bis; try { // URL url = new URL(this.getRemoteFileUrl(remoteFile)); // URLConnection urlFtpConnection = url.openConnection(); InputStream is = new FileInputStream(localfilename); bis = new BufferedInputStream(is); connect2Server(); if (oFtp.isConnected()) { String fileExtension = localfilename.substring(localfilename.lastIndexOf(".") + 1); String[] fileExtensions = {"png", "gif", "bmp", "jpg", "jpeg", "tiff"}; // If exporting to .csv or .tsv, add the gid parameter to specify which sheet to export if (Arrays.asList(fileExtensions).contains(fileExtension)) { oFtp.setFileType(FTP.BINARY_FILE_TYPE); } // OutputStream os = oFtp.storeFileStream(remoteFile); // if (os == null) // { // logError(oFtp.getReplyString()); // } // BufferedOutputStream bos = new BufferedOutputStream(os); // byte[] buffer = new byte[1024]; // int readCount; // // while ((readCount = bis.read(buffer)) > 0) // { // bos.write(buffer); // // bos.flush(); // } // bos.close(); if (!oFtp.storeFile(remoteFile, bis)) { logError( "Can't upload file " + localfilename + " FTP reply code: " + oFtp.getReplyCode() + " Ftp message: " + oFtp.getReplyString()); bis.close(); is.close(); this.closeFtpConnection(); return false; } else { logMessage("File `" + localfilename + "` is uploaded!"); } } /* * urlFtpConnection.getOutputStream(); * // * log.message("File `" + localfilename + "` is uploaded!"); */ bis.close(); is.close(); // this.closeFtpConnection(); return true; } catch (Exception ex) { StringWriter sw0 = new StringWriter(); PrintWriter p0 = new PrintWriter(sw0, true); ex.printStackTrace(p0); log.error(sw0.getBuffer().toString()); log.exception(ex); return false; } }
public String ftpGet( String remoteAddr, int remotePort, String remotePath, String remoteFileName, String localPath, String username, String password) throws SocketException, IOException { FTPClient ftp = new FTPClient(); FTPClientConfig config = new FTPClientConfig(); ftp.configure(config); try { ftp.connect(remoteAddr, remotePort); log.debug("Connected to " + remoteAddr + ":" + remotePort + ".\n" + ftp.getReplyString()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); log.error("FTP server refused connection."); throw new RuntimeException("FTP server refused connection."); } ftp.login(username, password); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); log.error("FTP server refused connection."); throw new RuntimeException("FTP server refused connection."); } if (!ftp.setFileType(FTP.BINARY_FILE_TYPE)) { log.error("set BINARY_FILE_TYPE error."); throw new RuntimeException("FTP server refused connection."); } // ftp.setFileTransferMode(FTPClient.STREAM_TRANSFER_MODE); ftp.enterLocalPassiveMode(); String remote = remotePath + "/" + remoteFileName; String local = localPath + "/" + remoteFileName; String returnName = genFileName(local); File f = new File(returnName); FileOutputStream fos = FileUtils.openOutputStream(f); try { long startTime = System.currentTimeMillis(); if (!ftp.retrieveFile(remote, fos)) { log.error("get " + remote + " error."); throw new RuntimeException("get " + remote + " error."); } log.debug("get remote file[" + remote + "], local file[" + local + "] ."); long finishedTime = System.currentTimeMillis(); log.debug("remote time :" + (finishedTime - startTime) / 1000f + " sec."); } finally { IOUtils.closeQuietly(fos); } ftp.logout(); return returnName; } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } }
/** @param args */ public static void main(String[] args) throws Exception { Properties prop = PropertiesLoader.loadProp("ftp.config.properties"); String serverAddress = prop.getProperty("ftp.address"); int serverPort = Integer.parseInt(prop.getProperty("ftp.port")); String userId = prop.getProperty("ftp.id"); String userPassword = prop.getProperty("ftp.password"); String localDir = prop.getProperty("ftp.localDir"); String remoteDir = prop.getProperty("ftp.remoteDir"); String logDir = prop.getProperty("ftp.logDir"); FTPClient ftp = new FTPClient(); FTPClientConfig config = new FTPClientConfig(); ftp.configure(config); boolean error = false; try { int reply; ftp.connect(serverAddress, serverPort); System.out.println("Connected to " + prop.getProperty("ftp.address") + "."); reply = ftp.getReplyCode(); System.out.print(ftp.getReplyString()); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } if (!ftp.login(userId, userPassword)) { ftp.logout(); throw new Exception("FTP 서버에 로그인하지 못했습니다."); } ftp.changeWorkingDirectory(remoteDir); FTPFile[] files = ftp.listFiles(); System.out.println("Number of files in dir: " + files.length); // Open log file String logFile = new SimpleDateFormat("yyyyMMddhhmm").format(new Date()); FileWriter fw = new FileWriter(logDir + "/" + logFile + ".txt", true); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { } else { System.out.println(files[i].getName()); File file = new File(localDir + File.separator + files[i].getName()); FileOutputStream fos = new FileOutputStream(file); ftp.retrieveFile(files[i].getName(), fos); fos.close(); // Format the date String theTime = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT) .format(new Date()); fw.write("FTP'd " + files[i].getName() + " at " + theTime + "\n"); } } fw.close(); System.out.println("done!"); ftp.logout(); } catch (IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } // System.exit(error ? 1 : 0); } }