Java Code Examples for org.apache.commons.net.ftp.FTPClient#getReplyCode()
The following examples show how to use
org.apache.commons.net.ftp.FTPClient#getReplyCode() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FTPClientFactory.java From hsweb-framework with Apache License 2.0 | 6 votes |
public PooledObject<FTPClient> makeObject() throws Exception { FTPClient ftpClient = new FTPClient(); ftpClient.setConnectTimeout(config.getClientTimeout()); ftpClient.connect(config.getHost(), config.getPort()); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); logger.warn("FTPServer refused connection"); return null; } boolean result = ftpClient.login(config.getUsername(), config.getPassword()); if (!result) { throw new ConnectException("ftp登陆失败:" + config.getUsername() + "/password:" + config.getPassword() + "@" + config.getHost()); } ftpClient.setFileType(config.getTransferFileType()); ftpClient.setBufferSize(1024); ftpClient.setControlEncoding(config.getEncoding()); if (config.isPassiveMode()) { ftpClient.enterLocalPassiveMode(); } return new DefaultPooledObject<>(ftpClient); }
Example 2
Source File: FTPUploader.java From azure-gradle-plugins with MIT License | 6 votes |
/** * Upload a single file to FTP server with the provided FTP client object. * * @param sourceFilePath * @param targetFilePath * @param logPrefix * @throws IOException */ private void uploadFile(final FTPClient ftpClient, final String sourceFilePath, final String targetFilePath, final String logPrefix) throws IOException { logger.quiet(String.format(UPLOAD_FILE, logPrefix, sourceFilePath, targetFilePath)); final File sourceFile = new File(sourceFilePath); try (final InputStream is = new FileInputStream(sourceFile)) { ftpClient.changeWorkingDirectory(targetFilePath); ftpClient.storeFile(sourceFile.getName(), is); final int replyCode = ftpClient.getReplyCode(); final String replyMessage = ftpClient.getReplyString(); if (isCommandFailed(replyCode)) { logger.error(String.format(UPLOAD_FILE_REPLY, logPrefix, replyMessage)); throw new IOException("Failed to upload file: " + sourceFilePath); } else { logger.quiet(String.format(UPLOAD_FILE_REPLY, logPrefix, replyMessage)); } } }
Example 3
Source File: FTPUploader.java From azure-gradle-plugins with MIT License | 6 votes |
/** * Upload a single file to FTP server with the provided FTP client object. * * @param sourceFilePath * @param targetFilePath * @param logPrefix * @throws IOException */ protected void uploadFile(final FTPClient ftpClient, final String sourceFilePath, final String targetFilePath, final String logPrefix) throws IOException { logger.quiet(String.format(UPLOAD_FILE, logPrefix, sourceFilePath, targetFilePath)); final File sourceFile = new File(sourceFilePath); try (final InputStream is = new FileInputStream(sourceFile)) { ftpClient.changeWorkingDirectory(targetFilePath); ftpClient.storeFile(sourceFile.getName(), is); final int replyCode = ftpClient.getReplyCode(); final String replyMessage = ftpClient.getReplyString(); if (isCommandFailed(replyCode)) { logger.error(String.format(UPLOAD_FILE_REPLY, logPrefix, replyMessage)); throw new IOException("Failed to upload file: " + sourceFilePath); } else { logger.quiet(String.format(UPLOAD_FILE_REPLY, logPrefix, replyMessage)); } } }
Example 4
Source File: FTPOperationHandler.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 5 votes |
@Override public WritableByteChannel append() throws IOException { FTPClient ftp = null; try { ftp = connect(uri); Info info = info(uri, ftp); if ((info != null) && info.isDirectory()) { throw new IOException(MessageFormat.format(FileOperationMessages.getString("IOperationHandler.exists_not_file"), uri)); //$NON-NLS-1$ } OutputStream os = ftp.appendFileStream(getPath(uri)); if (os == null) { throw new IOException(ftp.getReplyString()); } int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveIntermediate(replyCode) && !FTPReply.isPositivePreliminary(replyCode)) { os.close(); throw new IOException(ftp.getReplyString()); } return Channels.newChannel(new FTPOutputStream(os, ftp)); } catch (Throwable t) { disconnect(ftp); if (t instanceof IOException) { throw (IOException) t; } else { throw new IOException(t); } } }
Example 5
Source File: FtpUtils.java From kkFileView with Apache License 2.0 | 5 votes |
public static FTPClient connect(String host, int port, String username, String password, String controlEncoding) throws IOException { FTPClient ftpClient = new FTPClient(); ftpClient.connect(host, port); if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) { ftpClient.login(username, password); } int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); } ftpClient.setControlEncoding(controlEncoding); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); return ftpClient; }
Example 6
Source File: FtpUtil.java From learning-taotaoMall with MIT License | 5 votes |
/** * 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; }
Example 7
Source File: FTPDownloader.java From journaldev with MIT License | 5 votes |
public FTPDownloader(String host, String user, String pwd) throws Exception { ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); int reply; ftp.connect(host); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new Exception("Exception in connecting to FTP Server"); } ftp.login(user, pwd); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); }
Example 8
Source File: FTPOperationHandler.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 5 votes |
protected FTPClient connect(URI uri) throws IOException { FTPClient ftp = new FTPClient(); // FTPClientConfig config = new FTPClientConfig(); // config.setServerTimeZoneId("GMT+0"); // ftp.configure(config); ftp.setListHiddenFiles(true); UserInfo userInfo = UserInfo.fromURI(uri); try { int port = uri.getPort(); if (port < 0) { port = 21; } ftp.connect(uri.getHost(), port); if (!ftp.login(userInfo.getUser(), userInfo.getPassword())) { ftp.logout(); throw new IOException(FileOperationMessages.getString("FTPOperationHandler.authentication_failed")); //$NON-NLS-1$ } ftp.enterLocalPassiveMode(); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException(FileOperationMessages.getString("FTPOperationHandler.connection_failed")); //$NON-NLS-1$ } return ftp; } catch (IOException ioe) { disconnect(ftp); throw new IOException(FileOperationMessages.getString("FTPOperationHandler.connection_failed"), ioe); //$NON-NLS-1$ } }
Example 9
Source File: FtpFileAdaptor.java From xenon with Apache License 2.0 | 5 votes |
private void login(Credential credential, FTPClient ftp) throws XenonException { try { loginWithCredentialOrDefault(ftp, credential); int replyCode = ftp.getReplyCode(); verifyLoginSuccess(replyCode); } catch (XenonException | IOException e) { throw new XenonException(getName(), "Failed to login", e); } }
Example 10
Source File: TestCase.java From springboot-ureport with Apache License 2.0 | 5 votes |
/** * Description: 向FTP服务器上传文件 * @Version1.0 Jul 27, 2008 4:31:09 PM by 崔红保([email protected])创建 * @param url FTP服务器hostname * @param port FTP服务器端口 * @param username FTP登录账号 * @param password FTP登录密码 * @param path FTP服务器保存目录 * @param filename 上传到FTP服务器上的文件名 * @param input 输入流 * @return 成功返回true,否则返回false */ public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) { boolean success = false; FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(url, port);//连接FTP服务器 //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器 ftp.login(username, password);//登录 reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } ftp.changeWorkingDirectory(path); ftp.storeFile(filename, input); input.close(); ftp.logout(); success = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return success; }
Example 11
Source File: FtpClient.java From tutorials with MIT License | 5 votes |
void open() throws IOException { ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); ftp.connect(server, port); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("Exception in connecting to FTP Server"); } ftp.login(user, password); }
Example 12
Source File: FTPServerTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 4 votes |
/** * Test CWD for FTP server * * @throws Exception */ public void testCWD() throws Exception { logger.debug("Start testCWD"); FTPClient ftp = connectClient(); try { int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { fail("FTP server refused connection."); } boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN); assertTrue("admin login successful", login); FTPFile[] files = ftp.listFiles(); reply = ftp.getReplyCode(); assertTrue(FTPReply.isPositiveCompletion(reply)); assertTrue(files.length == 1); boolean foundAlfresco=false; for(FTPFile file : files) { logger.debug("file name=" + file.getName()); assertTrue(file.isDirectory()); if(file.getName().equalsIgnoreCase("Alfresco")) { foundAlfresco=true; } } assertTrue(foundAlfresco); // Change to Alfresco Dir that we know exists reply = ftp.cwd("/Alfresco"); assertTrue(FTPReply.isPositiveCompletion(reply)); // relative path with space char reply = ftp.cwd("Data Dictionary"); assertTrue(FTPReply.isPositiveCompletion(reply)); // non existant absolute reply = ftp.cwd("/Garbage"); assertTrue(FTPReply.isNegativePermanent(reply)); reply = ftp.cwd("/Alfresco/User Homes"); assertTrue(FTPReply.isPositiveCompletion(reply)); // Wild card reply = ftp.cwd("/Alfresco/User*Homes"); assertTrue("unable to change to /Alfresco User*Homes/", FTPReply.isPositiveCompletion(reply)); // // Single char pattern match // reply = ftp.cwd("/Alfre?co"); // assertTrue("Unable to match single char /Alfre?co", FTPReply.isPositiveCompletion(reply)); // two level folder reply = ftp.cwd("/Alfresco/Data Dictionary"); assertTrue("unable to change to /Alfresco/Data Dictionary", FTPReply.isPositiveCompletion(reply)); // go up one reply = ftp.cwd(".."); assertTrue("unable to change to ..", FTPReply.isPositiveCompletion(reply)); reply = ftp.pwd(); ftp.getStatus(); assertTrue("unable to get status", FTPReply.isPositiveCompletion(reply)); // check we are at the correct point in the tree reply = ftp.cwd("Data Dictionary"); assertTrue(FTPReply.isPositiveCompletion(reply)); } finally { ftp.disconnect(); } }
Example 13
Source File: FTPServerTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 4 votes |
/** * Test CRUD for FTP server * * @throws Exception */ public void testCRUD() throws Exception { final String PATH1 = "FTPServerTest"; final String PATH2 = "Second part"; logger.debug("Start testFTPCRUD"); FTPClient ftp = connectClient(); try { int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { fail("FTP server refused connection."); } boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN); assertTrue("admin login successful", login); reply = ftp.cwd("/Alfresco/User Homes"); assertTrue(FTPReply.isPositiveCompletion(reply)); // Delete the root directory in case it was left over from a previous test run try { ftp.removeDirectory(PATH1); } catch (IOException e) { // ignore this error } // make root directory ftp.makeDirectory(PATH1); ftp.cwd(PATH1); // make sub-directory in new directory ftp.makeDirectory(PATH2); ftp.cwd(PATH2); // List the files in the new directory FTPFile[] files = ftp.listFiles(); assertTrue("files not empty", files.length == 0); // Create a file String FILE1_CONTENT_1="test file 1 content"; String FILE1_NAME = "testFile1.txt"; ftp.appendFile(FILE1_NAME , new ByteArrayInputStream(FILE1_CONTENT_1.getBytes("UTF-8"))); // Get the new file FTPFile[] files2 = ftp.listFiles(); assertTrue("files not one", files2.length == 1); InputStream is = ftp.retrieveFileStream(FILE1_NAME); String content = inputStreamToString(is); assertEquals("Content is not as expected", content, FILE1_CONTENT_1); ftp.completePendingCommand(); // Update the file contents String FILE1_CONTENT_2="That's how it is says Pooh!"; ftp.storeFile(FILE1_NAME , new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8"))); InputStream is2 = ftp.retrieveFileStream(FILE1_NAME); String content2 = inputStreamToString(is2); assertEquals("Content is not as expected", FILE1_CONTENT_2, content2); ftp.completePendingCommand(); // now delete the file we have been using. assertTrue (ftp.deleteFile(FILE1_NAME)); // negative test - file should have gone now. assertFalse (ftp.deleteFile(FILE1_NAME)); } finally { // clean up tree if left over from previous run ftp.disconnect(); } }
Example 14
Source File: CfdaServiceImpl.java From kfs with GNU Affero General Public License v3.0 | 4 votes |
/** * @return * @throws IOException */ public SortedMap<String, CFDA> getGovCodes() throws IOException { Calendar calendar = dateTimeService.getCurrentCalendar(); SortedMap<String, CFDA> govMap = new TreeMap<String, CFDA>(); // ftp://ftp.cfda.gov/programs09187.csv String govURL = parameterService.getParameterValueAsString(CfdaBatchStep.class, KFSConstants.SOURCE_URL_PARAMETER); String fileName = StringUtils.substringAfterLast(govURL, "/"); govURL = StringUtils.substringBeforeLast(govURL, "/"); if (StringUtils.contains(govURL, "ftp://")) { govURL = StringUtils.remove(govURL, "ftp://"); } // need to pull off the '20' in 2009 String year = "" + calendar.get(Calendar.YEAR); year = year.substring(2, 4); fileName = fileName + year; // the last 3 numbers in the file name are the day of the year, but the files are from "yesterday" fileName = fileName + String.format("%03d", calendar.get(Calendar.DAY_OF_YEAR) - 1); fileName = fileName + ".csv"; LOG.info("Getting government file: " + fileName + " for update"); InputStream inputStream = null; FTPClient ftp = new FTPClient(); try { ftp.connect(govURL); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { LOG.error("FTP connection to server not established."); throw new IOException("FTP connection to server not established."); } boolean isLoggedIn = ftp.login("anonymous", ""); if (!isLoggedIn) { LOG.error("Could not login as anonymous."); throw new IOException("Could not login as anonymous."); } LOG.info("Successfully connected and logged in"); ftp.enterLocalPassiveMode(); inputStream = ftp.retrieveFileStream(fileName); if (inputStream != null) { LOG.info("reading input stream"); InputStreamReader screenReader = new InputStreamReader(inputStream); BufferedReader screen = new BufferedReader(screenReader); CSVReader csvReader = new CSVReader(screenReader, ',', '"', 1); List<String[]> lines = csvReader.readAll(); for (String[] line : lines) { String title = line[0]; String number = line[1]; CFDA cfda = new CFDA(); cfda.setCfdaNumber(number); cfda.setCfdaProgramTitleName(title); govMap.put(number, cfda); } } ftp.logout(); ftp.disconnect(); } finally { if (ftp.isConnected()) { ftp.disconnect(); } } return govMap; }
Example 15
Source File: FTPServerTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 4 votes |
/** * Test of rename case ALF-20584 * */ public void testRenameCase() throws Exception { logger.debug("Start testRenameCase"); FTPClient ftp = connectClient(); String PATH1="testRenameCase"; try { int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { fail("FTP server refused connection."); } boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN); assertTrue("admin login successful", login); reply = ftp.cwd("/Alfresco/User*Homes"); assertTrue(FTPReply.isPositiveCompletion(reply)); // Delete the root directory in case it was left over from a previous test run try { ftp.removeDirectory(PATH1); } catch (IOException e) { // ignore this error } // make root directory for this test boolean success = ftp.makeDirectory(PATH1); assertTrue("unable to make directory:" + PATH1, success); ftp.cwd(PATH1); String FILE1_CONTENT_2="That's how it is says Pooh!"; ftp.storeFile("FileA.txt" , new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8"))); assertTrue("unable to rename", ftp.rename("FileA.txt", "FILEA.TXT")); } finally { // clean up tree if left over from previous run ftp.disconnect(); } }
Example 16
Source File: FTPService.java From cs-actions with Apache License 2.0 | 4 votes |
private void checkReply(String command, FTPClient ftp) throws FTPException { _sessionLog.append("> ").append(command).append("\r\n"); _sessionLog.append(ftp.getReplyString()).append("\r\n"); _replyCode = ftp.getReplyCode(); checkReplyCode(command, _replyCode, ftp); }
Example 17
Source File: FtpFileUtil.java From hsac-fitnesse-fixtures with Apache License 2.0 | 4 votes |
private static void validatResponse(FTPClient ftpClient) { if (FTPReply.isNegativeTransient(ftpClient.getReplyCode()) || FTPReply.isNegativePermanent(ftpClient.getReplyCode())) { throw new RuntimeException("Got error response: " + ftpClient.getReplyCode()); } }
Example 18
Source File: FTPServerTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 4 votes |
/** * Test for Passive Mode -> FTPCommand.Pasv command with external address functionality. * see MNT-16433 */ public void testFTPConnectExternalAddressSet() throws Exception { logger.debug("Start testFTPConnectExternalAddressSet"); try { // use a highly improbable IP to tests Passive Mode -> FTPCommand.Pasv command // this is supposed to be the address of a proxy in front of Alfrsco FTP server String improbableIPAddress = "127.255.255.42"; ftpConfigSection.setFTPExternalAddress(improbableIPAddress); FTPClient ftp = connectClient(); try { int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { fail("FTP server refused connection."); } boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN); assertTrue("admin login not successful", login); // activate passive mode boolean sucess = ftp.enterRemotePassiveMode(); assertTrue(sucess); assertTrue("Client should be in passive mode now", ftp.getDataConnectionMode() == FTPClient.PASSIVE_REMOTE_DATA_CONNECTION_MODE); reply = ftp.getReplyCode(); //see https://www.ietf.org/rfc/rfc959.txt assertTrue("reply code should be 227", reply == 227); String replyLine = ftp.getReplyString(); assertTrue(replyLine != null); String encodedImprobableIPAddress = improbableIPAddress.replaceAll("\\.", ","); assertTrue("Pasv command should contain the set external address encoded", replyLine.contains(encodedImprobableIPAddress)); // now attempt to list the files and check that the command does not succeed FTPFile[] files = ftp.listFiles(); assertNotNull(files); assertTrue("list command should not succeed", files.length == 0); assertTrue("The passive host should be the one set earlier.", improbableIPAddress.equals(ftp.getPassiveHost())); } finally { safeDisconnect(ftp); } } finally { //always revert back to default, or the other tests will fail ftpConfigSection.setFTPExternalAddress(null); } }
Example 19
Source File: FTPUtil.java From imageServer with Apache License 2.0 | 4 votes |
/** * 获取FTP连接对象 * @param ftpConnectAttr * FTP的连接配置 * @return * 获取异常失败则返回null */ public static FTPClient getFTPClient(FTPConnectAttr ftpConnectAttr){ if(ftpConnectAttr == null){ log.error("FTP的连接配置不能为Null"); return null; } if(ObjectUtil.isNull(ftpConnectAttr.address) || ObjectUtil.isNull(ftpConnectAttr.userName)){ log.error("连接地址或连接的用户名不能为空"); return null; } FTPClient ftpClient = new FTPClient(); try { String url = ftpConnectAttr.address; log.info("设置ftp地址:" + url); if(url.split(":").length == 2){ String[] us = url.split(":"); int port = Integer.valueOf(us[1]); ftpClient.connect(us[0],port); }else { ftpClient.connect(url); } ftpClient.setDataTimeout(120000); //设置传输超时时间为120秒 ftpClient.setConnectTimeout(120000); //连接超时为120秒 ftpClient.setControlEncoding("GBK"); log.info("设置登陆账号:" + ftpConnectAttr.userName + ":" + ftpConnectAttr.password); ftpClient.login(ftpConnectAttr.userName, ftpConnectAttr.password); int reply = ftpClient.getReplyCode(); if(String.valueOf(reply).indexOf("2") != 0){ log.error("ftp连接失败,返回值:" + reply); if(ftpClient.isConnected()){ ftpClient.disconnect(); return null; } } log.info("ftp连接成功,返回值:" + reply); } catch (IOException e) { log.error("获取FTPClient发生错误,返回null",e); if(ftpClient.isConnected()){ try { ftpClient.disconnect(); } catch (IOException ignored) { } } return null; } return ftpClient; }
Example 20
Source File: FTPFileSystem.java From RDFS with Apache License 2.0 | 4 votes |
/** * A stream obtained via this call must be closed before using other APIs of * this class or else the invocation will block. */ @Override public FSDataOutputStream create(Path file, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { final FTPClient client = connect(); Path workDir = new Path(client.printWorkingDirectory()); Path absolute = makeAbsolute(workDir, file); if (exists(client, file)) { if (overwrite) { delete(client, file); } else { disconnect(client); throw new IOException("File already exists: " + file); } } Path parent = absolute.getParent(); if (parent == null || !mkdirs(client, parent, FsPermission.getDefault())) { parent = (parent == null) ? new Path("/") : parent; disconnect(client); throw new IOException("create(): Mkdirs failed to create: " + parent); } client.allocate(bufferSize); // Change to parent directory on the server. Only then can we write to the // file on the server by opening up an OutputStream. As a side effect the // working directory on the server is changed to the parent directory of the // file. The FTP client connection is closed when close() is called on the // FSDataOutputStream. client.changeWorkingDirectory(parent.toUri().getPath()); FSDataOutputStream fos = new FSDataOutputStream(client.storeFileStream(file .getName()), statistics) { @Override public void close() throws IOException { super.close(); if (!client.isConnected()) { throw new FTPException("Client not connected"); } boolean cmdCompleted = client.completePendingCommand(); disconnect(client); if (!cmdCompleted) { throw new FTPException("Could not complete transfer, Reply Code - " + client.getReplyCode()); } } }; if (!FTPReply.isPositivePreliminary(client.getReplyCode())) { // The ftpClient is an inconsistent state. Must close the stream // which in turn will logout and disconnect from FTP server fos.close(); throw new IOException("Unable to create file: " + file + ", Aborting"); } return fos; }