Java Code Examples for org.apache.commons.net.ftp.FTPClient#login()
The following examples show how to use
org.apache.commons.net.ftp.FTPClient#login() .
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: FtpHelper.java From openemm with GNU Affero General Public License v3.0 | 6 votes |
/** * Connect. * * @throws Exception the exception */ @Override public void connect() throws Exception { try { ftpClient = new FTPClient(); ftpClient.connect(host, port); if (usePassiveMode) { ftpClient.enterLocalPassiveMode(); } if (!ftpClient.login(user, password)) { ftpClient.logout(); throw new Exception("Authentication failed"); } } catch (Exception e) { close(); throw new Exception("Connection failed"); } }
Example 2
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 3
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 4
Source File: BugReportSenderFtp.java From YalpStore with GNU General Public License v2.0 | 6 votes |
private boolean uploadAll() { FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(FTP_HOST, FTP_PORT); if (!ftpClient.login(FTP_USER, FTP_PASSWORD)) { return false; } String dirName = getDirName(); ftpClient.makeDirectory(dirName); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE); ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE); boolean result = true; for (File file: files) { result &= upload(ftpClient, file, dirName + "/" + file.getName()); } return result; } catch (IOException e) { Log.e(BugReportSenderFtp.class.getSimpleName(), "FTP network error: " + e.getMessage()); } finally { closeSilently(ftpClient); } return false; }
Example 5
Source File: FTPUtil.java From MeetingFilm with Apache License 2.0 | 5 votes |
private void initFTPClient(){ try{ ftpClient = new FTPClient(); ftpClient.setControlEncoding("utf-8"); ftpClient.connect(hostName,port); ftpClient.login(userName,password); }catch (Exception e){ log.error("初始化FTP失败",e); } }
Example 6
Source File: FTPUploader.java From azure-gradle-plugins with MIT License | 5 votes |
private FTPClient getFTPClient(final String ftpServer, final String username, final String password) throws Exception { final FTPClient ftpClient = new FTPClient(); ftpClient.connect(ftpServer); ftpClient.login(username, password); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); return ftpClient; }
Example 7
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 8
Source File: FTPClientTemplate.java From MicroCommunity with Apache License 2.0 | 5 votes |
/** * 连接到ftp服务器 * * @param ftpClient * @return 连接成功返回true,否则返回false * @throws Exception */ private boolean connect(FTPClient ftpClient)throws Exception { try { ftpClient.connect(host, port); // 连接后检测返回码来校验连接是否成功 int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { //登陆到ftp服务器 if (ftpClient.login(username, password)) { setFileType(ftpClient); return true; } } else { ftpClient.disconnect(); throw new Exception("FTP server refused connection."); } } catch (IOException e) { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); //断开连接 } catch (IOException e1) { throw new Exception("Could not disconnect from server.", e1); } } throw new Exception("Could not connect to server.", e); } return false; }
Example 9
Source File: FTPUtil.java From mmall20180107 with Apache License 2.0 | 5 votes |
private boolean connectServer(String ip,int port,String user,String pwd){ boolean isSuccess = false; ftpClient = new FTPClient(); try { ftpClient.connect(ip); isSuccess = ftpClient.login(user,pwd); } catch (IOException e) { logger.error("连接FTP服务器异常",e); } return isSuccess; }
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: 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: FtpVerifierExtension.java From syndesis with Apache License 2.0 | 4 votes |
private static void verifyCredentials(ResultBuilder builder, Map<String, Object> parameters) { final String host = ConnectorOptions.extractOption(parameters, "host"); final Integer port = ConnectorOptions.extractOptionAndMap(parameters, "port", Integer::parseInt, 21); final String userName = ConnectorOptions.extractOption(parameters, "username", "anonymous"); String password = ""; if (! "anonymous".equals(userName)) { password = ConnectorOptions.extractOption(parameters, "password", password); } int reply; FTPClient ftp = new FTPClient(); String illegalParametersMessage = "Unable to connect to the FTP server"; boolean hasValidParameters = false; try { ftp.connect(host, port); reply = ftp.getReplyCode(); hasValidParameters = FTPReply.isPositiveCompletion(reply); } catch (IOException e) { illegalParametersMessage = e.getMessage(); } if (!hasValidParameters) { builder.error( ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.ILLEGAL_PARAMETER_VALUE, illegalParametersMessage).parameterKey("host").parameterKey("port").build()); } else { boolean isAuthenticated = false; String authentionErrorMessage = "Authentication failed"; try { isAuthenticated = ftp.login(userName, password); } catch (IOException ioe) { authentionErrorMessage = ioe.getMessage(); } if (!isAuthenticated) { builder.error(ResultErrorBuilder .withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, authentionErrorMessage) .parameterKey("username").parameterKey("password").build()); } else { try { ftp.logout(); ftp.disconnect(); } catch (IOException ignored) { // ignore } } } }
Example 13
Source File: DownloadFileFromFtpToTable.java From MicroCommunity with Apache License 2.0 | 4 votes |
/** * 下载文件并且存至tfs文件系统 * * @param remoteFileNameTmp * @param * @return */ private Map downLoadFileToTable(String remoteFileNameTmp, FTPClientTemplate ftpClientTemplate, Map ftpItemConfigInfo) { Map resultInfo = new HashMap(); String tfsReturnFileName = null; long block = 10 * 1024;// 默认 if (ftpClientTemplate == null) { resultInfo.put("SAVE_FILE_FLAG", "E"); return resultInfo; } String localPathName = ftpItemConfigInfo.get("localPath").toString().endsWith("/") ? ftpItemConfigInfo.get("localPath").toString() + ftpItemConfigInfo.get("newFileName").toString() : ftpItemConfigInfo.get("localPath").toString() + "/" + ftpItemConfigInfo.get("newFileName").toString(); ftpItemConfigInfo.put("localfilename", localPathName);// 本地带路径的文件名回写,后面读文件时使用 try { File file = new File(localPathName); RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");// 建立随机访问 FTPClient ftpClient = new FTPClient(); ftpClient.connect(ftpClientTemplate.getHost(), ftpClientTemplate.getPort()); if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { if (!ftpClient.login(ftpClientTemplate.getUsername(), ftpClientTemplate.getPassword())) { resultInfo.put("SAVE_FILE_FLAG", "E"); resultInfo.put("remark", "登录失败,用户名【" + ftpClientTemplate.getUsername() + "】密码【" + ftpClientTemplate.getPassword() + "】"); return resultInfo; } } ftpClient.setControlEncoding("UTF-8"); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 二进制 ftpClient.enterLocalPassiveMode(); // 被动模式 ftpClient.sendCommand("PASV"); ftpClient.sendCommand("SIZE " + remoteFileNameTmp + "\r\n"); String replystr = ftpClient.getReplyString(); String[] replystrL = replystr.split(" "); long filelen = 0; if (Integer.valueOf(replystrL[0]) == 213) { filelen = Long.valueOf(replystrL[1].trim()); } else { resultInfo.put("SAVE_FILE_FLAG", "E"); resultInfo.put("remark", "无法获取要下载的文件的大小!"); return resultInfo; } accessFile.setLength(filelen); accessFile.close(); ftpClient.disconnect(); int tnum = Integer.valueOf(ftpItemConfigInfo.get("TNUM").toString()); block = (filelen + tnum - 1) / tnum;// 每个线程下载的快大小 ThreadPoolExecutor cachedThreadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool(); List<Future<Map>> threadR = new ArrayList<Future<Map>>(); for (int i = 0; i < tnum; i++) { logger.debug("发起线程:" + i); // 保存线程日志 ftpItemConfigInfo.put("threadrunstate", "R"); ftpItemConfigInfo.put("remark", "开始下载文件"); ftpItemConfigInfo.put("data", "文件名:" + remoteFileNameTmp); long start = i * block; long end = (i + 1) * block - 1; ftpItemConfigInfo.put("begin", start); ftpItemConfigInfo.put("end", end); saveTaskLogDetail(ftpItemConfigInfo); Map para = new HashMap(); para.putAll(ftpItemConfigInfo); para.put("serverfilename", remoteFileNameTmp); para.put("filelength", filelen); para.put("tnum", i + 0); para.put("threadDownSize", block); para.put("transferflag", FTPClientTemplate.TransferType.download); FTPClientTemplate dumpThread = new FTPClientTemplate(para); Future<Map> runresult = cachedThreadPool.submit(dumpThread); threadR.add(runresult); } do { // 等待下载完成 Thread.sleep(1000); } while (cachedThreadPool.getCompletedTaskCount() < threadR.size()); saveDownFileData(ftpItemConfigInfo); // 下载已经完成,多线程保存数据至表中 } catch (Exception e) { // TODO Auto-generated catch block logger.error("保存文件失败:", e); resultInfo.put("SAVE_FILE_FLAG", "E"); resultInfo.put("remark", "保存文件失败:" + e); return resultInfo; } resultInfo.put("SAVE_FILE_FLAG", "S"); return resultInfo; }
Example 14
Source File: FTPService.java From cs-actions with Apache License 2.0 | 4 votes |
private void login(FTPClient ftp, String user, String password) throws FTPException, IOException { ftp.login(user, password); checkReply("user " + user, ftp); }
Example 15
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 16
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 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: FTPServerTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 4 votes |
/** * Test of obscure path names in the FTP server * * RFC959 states that paths are constructed thus... * <string> ::= <char> | <char><string> * <pathname> ::= <string> * <char> ::= any of the 128 ASCII characters except <CR> and <LF> * * So we need to check how high characters and problematic are encoded */ public void testPathNames() throws Exception { logger.debug("Start testPathNames"); FTPClient ftp = connectClient(); String PATH1="testPathNames"; 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); success = ftp.changeWorkingDirectory(PATH1); assertTrue("unable to change to working directory:" + PATH1, success); assertTrue("with a space", ftp.makeDirectory("test space")); assertTrue("with exclamation", ftp.makeDirectory("space!")); assertTrue("with dollar", ftp.makeDirectory("space$")); assertTrue("with brackets", ftp.makeDirectory("space()")); assertTrue("with hash curley brackets", ftp.makeDirectory("space{}")); //Pound sign U+00A3 //Yen Sign U+00A5 //Capital Omega U+03A9 assertTrue("with pound sign", ftp.makeDirectory("pound \u00A3.world")); assertTrue("with yen sign", ftp.makeDirectory("yen \u00A5.world")); // Test steps that do not work // assertTrue("with omega", ftp.makeDirectory("omega \u03A9.world")); // assertTrue("with obscure ASCII chars", ftp.makeDirectory("?/.,<>")); } finally { // clean up tree if left over from previous run ftp.disconnect(); } }
Example 19
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 20
Source File: RinexNavigation.java From GNSS_Compare with Apache License 2.0 | 4 votes |
private RinexNavigationParserGps getFromFTP(String url) throws IOException{ RinexNavigationParserGps rnp = null; String origurl = url; if(negativeChache.containsKey(url)){ if(System.currentTimeMillis()-negativeChache.get(url).getTime() < 60*60*1000){ throw new FileNotFoundException("cached answer"); }else{ negativeChache.remove(url); } } String filename = url.replaceAll("[ ,/:]", "_"); if(filename.endsWith(".Z")) filename = filename.substring(0, filename.length()-2); File rnf = new File(RNP_CACHE,filename); if(rnf.exists()){ System.out.println(url+" from cache file "+rnf); rnp = new RinexNavigationParserGps(rnf); try{ rnp.init(); return rnp; } catch( Exception e ){ rnf.delete(); } } // if the file doesn't exist of is invalid System.out.println(url+" from the net."); FTPClient ftp = new FTPClient(); try { int reply; System.out.println("URL: "+url); url = url.substring("ftp://".length()); String server = url.substring(0, url.indexOf('/')); String remoteFile = url.substring(url.indexOf('/')); String remotePath = remoteFile.substring(0,remoteFile.lastIndexOf('/')); remoteFile = remoteFile.substring(remoteFile.lastIndexOf('/')+1); ftp.connect(server); ftp.login("anonymous", "[email protected]"); 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."); return null; } ftp.enterLocalPassiveMode(); ftp.setRemoteVerificationEnabled(false); System.out.println("cwd to "+remotePath+" "+ftp.changeWorkingDirectory(remotePath)); System.out.println(ftp.getReplyString()); ftp.setFileType(FTP.BINARY_FILE_TYPE); System.out.println(ftp.getReplyString()); System.out.println("open "+remoteFile); InputStream is = ftp.retrieveFileStream(remoteFile); System.out.println(ftp.getReplyString()); if(ftp.getReplyString().startsWith("550")){ negativeChache.put(origurl, new Date()); throw new FileNotFoundException(); } InputStream uis = is; if(remoteFile.endsWith(".Z")){ uis = new UncompressInputStream(is); } rnp = new RinexNavigationParserGps(uis,rnf); rnp.init(); is.close(); ftp.completePendingCommand(); ftp.logout(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { // do nothing } } } return rnp; }