Java Code Examples for org.apache.commons.net.ftp.FTPClient#setFileType()
The following examples show how to use
org.apache.commons.net.ftp.FTPClient#setFileType() .
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: FtpConnection.java From xian with Apache License 2.0 | 6 votes |
FTPClient connect(String path, String addr, int port, String username, String password) throws Exception { FTPClient ftp = new FTPClient(); int reply; ftp.connect(addr, port); ftp.login(username, password); ftp.configure(new FTPClientConfig(ftp.getSystemType())); ftp.setControlEncoding("UTF-8"); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return null; } ftp.changeWorkingDirectory(path); return ftp; }
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: 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 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: 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 6
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 7
Source File: RomLoader.java From zxpoly with GNU General Public License v3.0 | 5 votes |
static byte[] loadFTPArchive(final String host, final String path, final String name, final String password) throws IOException { final FTPClient client = new FTPClient(); client.connect(host); int replyCode = client.getReplyCode(); if (FTPReply.isPositiveCompletion(replyCode)) { try { client.login(name == null ? "" : name, password == null ? "" : password); client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); final ByteArrayOutputStream out = new ByteArrayOutputStream(300000); if (client.retrieveFile(path, out)) { return out.toByteArray(); } else { throw new IOException( "Can't load file 'ftp://" + host + path + "\' status=" + client.getReplyCode()); } } finally { client.disconnect(); } } else { client.disconnect(); throw new IOException("Can't connect to ftp '" + host + "'"); } }
Example 8
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 9
Source File: FTPUploader.java From journaldev with MIT License | 5 votes |
public FTPUploader(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 10
Source File: PFtpClient.java From PHONK with GNU General Public License v3.0 | 5 votes |
@PhonkMethod(description = "Connect to a ftp server", example = "") @PhonkMethodParam(params = {"host", "port", "username", "password", "function(connected)"}) public void connect(final String host, final int port, final String username, final String password, final FtpConnectedCb callback) { mFTPClient = new FTPClient(); Thread t = new Thread(() -> { try { mFTPClient.connect(host, port); MLog.d(TAG, "1"); if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) { boolean logged = mFTPClient.login(username, password); mFTPClient.setFileType(FTP.BINARY_FILE_TYPE); mFTPClient.enterLocalPassiveMode(); isConnected = logged; callback.event(logged); } MLog.d(TAG, "" + isConnected); } catch (Exception e) { MLog.d(TAG, "connection failed error:" + e); } }); t.start(); }
Example 11
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 12
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 13
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 14
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 15
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 16
Source File: FTPUploader.java From azure-gradle-plugins with MIT License | 5 votes |
protected 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 17
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 18
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 19
Source File: FTPService.java From cs-actions with Apache License 2.0 | 4 votes |
private void setImageFileType(FTPClient ftp) throws IOException, FTPException { ftp.setFileType(FTPClient.BINARY_FILE_TYPE); checkReply("bin", ftp); }
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; }