Java Code Examples for org.apache.commons.net.ftp.FTPClient#storeFile()
The following examples show how to use
org.apache.commons.net.ftp.FTPClient#storeFile() .
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: TestCase.java From springboot-ureport with Apache License 2.0 | 6 votes |
@Test public void test2() throws Exception{ long start = System.currentTimeMillis(); File file = new File("E:/下载专用/test-fpt"); File[] listFiles = file.listFiles(); // int index = 1; for (File file2 : listFiles) { FileInputStream in = new FileInputStream(file2); FTPClient ftpClient = ftpClientPool.borrowObject(); // borrowObject.changeWorkingDirectory("/test"); String name = file2.getName(); name = new String(name.getBytes("GBK"),"iso-8859-1"); boolean storeFile = ftpClient.storeFile(name, in); System.out.println(storeFile); ftpClientPool.returnObject(ftpClient); // index++; // System.out.println(index); } long end = System.currentTimeMillis(); System.out.println("ok -> " + (end - start) ); }
Example 2
Source File: NetUtils.java From ApprovalTests.Java with Apache License 2.0 | 6 votes |
public static void ftpUpload(FTPConfig config, String directory, File file, String remoteFileName) throws IOException { FTPClient server = new FTPClient(); server.connect(config.host, config.port); assertValidReplyCode(server.getReplyCode(), server); server.login(config.userName, config.password); assertValidReplyCode(server.getReplyCode(), server); assertValidReplyCode(server.cwd(directory), server); server.setFileTransferMode(FTP.BINARY_FILE_TYPE); server.setFileType(FTP.BINARY_FILE_TYPE); server.storeFile(remoteFileName, new FileInputStream(file)); assertValidReplyCode(server.getReplyCode(), server); server.sendNoOp(); server.disconnect(); }
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 */ 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 4
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 5
Source File: FtpUtil.java From SSM with Apache License 2.0 | 6 votes |
public static boolean uploadPicture(String FTP_HOSTNAME,int FTP_PORT,String FTP_USERNAME,String FTP_PASSWORD,String FTP_REMOTE_PATH,String picName,InputStream fileInputStream)throws IOException { //创建一个FtpClient FTPClient ftpClient = new FTPClient(); //连接的ip和端口号 ftpClient.connect(FTP_HOSTNAME,FTP_PORT); //登陆的用户名和密码 ftpClient.login(FTP_USERNAME,FTP_PASSWORD); //将文件转换成输入流 //修改文件的存放地址 ftpClient.changeWorkingDirectory(FTP_REMOTE_PATH); //设置文件的上传格式 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //将我们的文件流以什么名字存放 boolean result = ftpClient.storeFile(picName,fileInputStream); //退出 ftpClient.logout(); return result; }
Example 6
Source File: FTPUtil.java From seed with Apache License 2.0 | 6 votes |
/** * 上传文件 * <p> * 该方法与{@link #uploadAndLogout(String, String, String, String, InputStream)}的区别是: * 上传完文件后没有登出服务器及释放连接,但会关闭输入流; * 之所以提供该方法是用于同时上传多个文件的情况下,使之能够共用一个FTP连接 * </p> * @param hostname 目标主机地址 * @param username FTP登录用户 * @param password FTP登录密码 * @param remoteURL 保存在FTP上的含完整路径和后缀的完整文件名 * @param is 文件输入流 * @return True if successfully completed, false if not. */ public static boolean upload(String hostname, String username, String password, String remoteURL, InputStream is){ if(!login(hostname, username, password, DEFAULT_DEFAULT_TIMEOUT, DEFAULT_CONNECT_TIMEOUT, DEFAULT_DATA_TIMEOUT)){ return false; } FTPClient ftpClient = ftpClientMap.get(); try{ remoteURL = FilenameUtils.separatorsToUnix(remoteURL); if(!ftpClient.changeWorkingDirectory(FilenameUtils.getFullPathNoEndSeparator(remoteURL))){ createRemoteFolder(ftpClient, FilenameUtils.getFullPathNoEndSeparator(remoteURL)); ftpClient.changeWorkingDirectory(FilenameUtils.getFullPathNoEndSeparator(remoteURL)); } String remoteFile = new String(FilenameUtils.getName(remoteURL).getBytes(DEFAULT_CHARSET), "ISO-8859-1"); ftpClient.setCopyStreamListener(new FTPProcess(is.available(), System.currentTimeMillis())); return ftpClient.storeFile(remoteFile, is); }catch(IOException e){ LogUtil.getLogger().error("文件["+remoteURL+"]上传到FTP服务器["+hostname+"]失败,堆栈轨迹如下", e); return false; }finally{ IOUtils.closeQuietly(is); } }
Example 7
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 8
Source File: Utils.java From azure-libraries-for-java with MIT License | 5 votes |
/** * Uploads a file to an Azure web app. * @param profile the publishing profile for the web app. * @param fileName the name of the file on server * @param file the local file */ public static void uploadFileToWebApp(PublishingProfile profile, String fileName, InputStream file) { FTPClient ftpClient = new FTPClient(); String[] ftpUrlSegments = profile.ftpUrl().split("/", 2); String server = ftpUrlSegments[0]; String path = "./site/wwwroot/webapps"; if (fileName.contains("/")) { int lastslash = fileName.lastIndexOf('/'); path = path + "/" + fileName.substring(0, lastslash); fileName = fileName.substring(lastslash + 1); } try { ftpClient.connect(server); ftpClient.login(profile.ftpUsername(), profile.ftpPassword()); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); for (String segment : path.split("/")) { if (!ftpClient.changeWorkingDirectory(segment)) { ftpClient.makeDirectory(segment); ftpClient.changeWorkingDirectory(segment); } } ftpClient.storeFile(fileName, file); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } }
Example 9
Source File: Utils.java From azure-libraries-for-java with MIT License | 5 votes |
/** * Uploads a file to an Azure function app. * @param profile the publishing profile for the web app. * @param fileName the name of the file on server * @param file the local file */ public static void uploadFileToFunctionApp(PublishingProfile profile, String fileName, InputStream file) { FTPClient ftpClient = new FTPClient(); String[] ftpUrlSegments = profile.ftpUrl().split("/", 2); String server = ftpUrlSegments[0]; String path = "site/wwwroot"; if (fileName.contains("/")) { int lastslash = fileName.lastIndexOf('/'); path = path + "/" + fileName.substring(0, lastslash); fileName = fileName.substring(lastslash + 1); } try { ftpClient.connect(server); ftpClient.login(profile.ftpUsername(), profile.ftpPassword()); ftpClient.setFileType(FTP.ASCII_FILE_TYPE); for (String segment : path.split("/")) { if (!ftpClient.changeWorkingDirectory(segment)) { ftpClient.makeDirectory(segment); ftpClient.changeWorkingDirectory(segment); } } ftpClient.storeFile(fileName, file); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } }
Example 10
Source File: Utils.java From azure-libraries-for-java with MIT License | 5 votes |
/** * Uploads a file to an Azure web app. * @param profile the publishing profile for the web app. * @param fileName the name of the file on server * @param file the local file */ public static void uploadFileToWebAppWwwRoot(PublishingProfile profile, String fileName, InputStream file) { FTPClient ftpClient = new FTPClient(); String[] ftpUrlSegments = profile.ftpUrl().split("/", 2); String server = ftpUrlSegments[0]; String path = "./site/wwwroot"; if (fileName.contains("/")) { int lastslash = fileName.lastIndexOf('/'); path = path + "/" + fileName.substring(0, lastslash); fileName = fileName.substring(lastslash + 1); } try { ftpClient.connect(server); ftpClient.login(profile.ftpUsername(), profile.ftpPassword()); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); for (String segment : path.split("/")) { if (!ftpClient.changeWorkingDirectory(segment)) { ftpClient.makeDirectory(segment); ftpClient.changeWorkingDirectory(segment); } } ftpClient.storeFile(fileName, file); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } }
Example 11
Source File: AppServiceTest.java From azure-libraries-for-java with MIT License | 5 votes |
/** * Uploads a file to an Azure web app. * @param profile the publishing profile for the web app. * @param fileName the name of the file on server * @param file the local file */ public static void uploadFileToWebApp(PublishingProfile profile, String fileName, InputStream file) { FTPClient ftpClient = new FTPClient(); String[] ftpUrlSegments = profile.ftpUrl().split("/", 2); String server = ftpUrlSegments[0]; String path = "./site/wwwroot/webapps"; if (fileName.contains("/")) { int lastslash = fileName.lastIndexOf('/'); path = path + "/" + fileName.substring(0, lastslash); fileName = fileName.substring(lastslash + 1); } try { ftpClient.connect(server); ftpClient.login(profile.ftpUsername(), profile.ftpPassword()); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); for (String segment : path.split("/")) { if (!ftpClient.changeWorkingDirectory(segment)) { ftpClient.makeDirectory(segment); ftpClient.changeWorkingDirectory(segment); } } ftpClient.storeFile(fileName, file); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } }
Example 12
Source File: PooledFTPOperationHandler.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 5 votes |
private boolean createFile(FTPClient ftp, String path) throws IOException { log.debug(MessageFormat.format("Creating {0}", path)); ftp.storeFile(path, new ByteArrayInputStream(new byte[0])); int replyCode = ftp.getReplyCode(); boolean result = FTPReply.isPositiveCompletion(replyCode) || FTPReply.isPositiveIntermediate(replyCode) || FTPReply.isPositivePreliminary(replyCode); if (!result) { result = FTPReply.isPositiveCompletion(replyCode); log.debug(MessageFormat.format("Failed to create {0}: {1}", path, ftp.getReplyString())); } return result; }
Example 13
Source File: Scar.java From scar with BSD 3-Clause "New" or "Revised" License | 5 votes |
static public boolean ftpUpload (String server, String user, String password, String dir, Paths paths, boolean passive) throws IOException { FTPClient ftp = new FTPClient(); InetAddress address = InetAddress.getByName(server); if (DEBUG) debug("scar", "Connecting to FTP server: " + address); ftp.connect(address); if (passive) ftp.enterLocalPassiveMode(); if (!ftp.login(user, password)) { if (ERROR) error("scar", "FTP login failed for user: " + user); return false; } if (!ftp.changeWorkingDirectory(dir)) { if (ERROR) error("scar", "FTP directory change failed: " + dir); return false; } ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); for (String path : paths) { if (INFO) info("scar", "FTP upload: " + path); BufferedInputStream input = new BufferedInputStream(new FileInputStream(path)); try { ftp.storeFile(new File(path).getName(), input); } finally { try { input.close(); } catch (Exception ignored) { } } } ftp.logout(); ftp.disconnect(); return true; }
Example 14
Source File: FTPClientUtils.java From springboot-ureport with Apache License 2.0 | 5 votes |
/** * FTP上传文件 * * @throws Exception */ public boolean uploadFile(String remote, InputStream local) { FTPClient ftpClient = borrowObject(); try { byte[] bytes = remote.getBytes("GBK"); return ftpClient.storeFile(new String(bytes, "iso-8859-1"), local); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); }finally { returnObject(ftpClient); } }
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: FTPServerTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 4 votes |
/** * Create a user other than "admin" who has access to a set of files. * * Create a folder containing test.docx as user one * Update that file as user two. * Check user one can see user two's changes. * * @throws Exception */ public void testTwoUserUpdate() throws Exception { logger.debug("Start testFTPConnect"); final String TEST_DIR="/Alfresco/User Homes/" + USER_ONE; FTPClient ftpOne = connectClient(); FTPClient ftpTwo = connectClient(); try { int reply = ftpOne.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { fail("FTP server refused connection."); } reply = ftpTwo.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { fail("FTP server refused connection."); } boolean login = ftpOne.login(USER_ONE, PASSWORD_ONE); assertTrue("user one login not successful", login); login = ftpTwo.login(USER_TWO, PASSWORD_TWO); assertTrue("user two login not successful", login); boolean success = ftpOne.changeWorkingDirectory("Alfresco"); assertTrue("user one unable to cd to Alfreco", success); success = ftpOne.changeWorkingDirectory("User*Homes"); assertTrue("user one unable to cd to User*Homes", success); success = ftpOne.changeWorkingDirectory(USER_ONE); assertTrue("user one unable to cd to " + USER_ONE, success); success = ftpTwo.changeWorkingDirectory("Alfresco"); assertTrue("user two unable to cd to Alfreco", success); success = ftpTwo.changeWorkingDirectory("User*Homes"); assertTrue("user two unable to cd to User*Homes", success); success = ftpTwo.changeWorkingDirectory(USER_ONE); assertTrue("user two unable to cd " + USER_ONE, success); // Create a file as user one String FILE1_CONTENT_1="test file 1 content"; String FILE1_NAME = "test.docx"; success = ftpOne.appendFile(FILE1_NAME , new ByteArrayInputStream(FILE1_CONTENT_1.getBytes("UTF-8"))); assertTrue("user one unable to append file", success); // Update the file as user two String FILE1_CONTENT_2="test file content updated"; success = ftpTwo.storeFile(FILE1_NAME , new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8"))); assertTrue("user two unable to append file", success); // User one should read user2's content InputStream is1 = ftpOne.retrieveFileStream(FILE1_NAME); assertNotNull("is1 is null", is1); String content1 = inputStreamToString(is1); assertEquals("Content is not as expected", FILE1_CONTENT_2, content1); ftpOne.completePendingCommand(); // User two should read user2's content InputStream is2 = ftpTwo.retrieveFileStream(FILE1_NAME); assertNotNull("is2 is null", is2); String content2 = inputStreamToString(is2); assertEquals("Content is not as expected", FILE1_CONTENT_2, content2); ftpTwo.completePendingCommand(); logger.debug("Test finished"); } finally { ftpOne.dele(TEST_DIR); if(ftpOne != null) { ftpOne.disconnect(); } if(ftpTwo != null) { ftpTwo.disconnect(); } } }
Example 17
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 18
Source File: FtpUtil.java From learning-taotaoMall with MIT License | 4 votes |
/** * 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; }
Example 19
Source File: FTPOperationHandler.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 4 votes |
private boolean createFile(FTPClient ftp, String path) throws IOException { return ftp.storeFile(path, new ByteArrayInputStream(new byte[0])); }
Example 20
Source File: FTPService.java From cs-actions with Apache License 2.0 | 4 votes |
private void putFile(FTPClient ftp, String remoteFilePath, InputStream in) throws IOException, FTPException { ftp.storeFile(remoteFilePath, in); checkReply("put " + remoteFilePath, ftp); }