java ftp
程序员文章站
2022-05-13 08:11:37
...
https://www.journaldev.com/661/java-ftp-client-upload-example-apache-commons-net
gradle依赖:
compile 'commons-net:commons-net:3.6'
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import org.apache.commons.net.PrintCommandListener; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; public class FTPUploader { FTPClient ftp = null; 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(); } public void uploadFile(String localFileFullName, String fileName, String hostDir) throws Exception { try(InputStream input = new FileInputStream(new File(localFileFullName))){ this.ftp.storeFile(hostDir + fileName, input); } } public void disconnect(){ if (this.ftp.isConnected()) { try { this.ftp.logout(); this.ftp.disconnect(); } catch (IOException f) { // do nothing as file is already saved to server } } } public static void main(String[] args) throws Exception { System.out.println("Start"); FTPUploader ftpUploader = new FTPUploader("ftp.journaldev.com", "ftpUser", "ftpPassword"); //FTP server path is relative. So if FTP account HOME directory is "/home/pankaj/public_html/" and you need to upload // files to "/home/pankaj/public_html/wp-content/uploads/image2/", you should pass directory parameter as "/wp-content/uploads/image2/" ftpUploader.uploadFile("D:\\Pankaj\\images\\MyImage.png", "image.png", "/wp-content/uploads/image2/"); ftpUploader.disconnect(); System.out.println("Done"); } }
上一篇: iptables场景二——ftp被动模式
下一篇: Linux FTP的安装与配置
推荐阅读
-
js获取当前系统时间年月日(java获取当前系统时间年月日)
-
java读取pdf文件内容(java获取pdf内容带格式)
-
java怎么使用数组(java新手代码大全)
-
java连接redis是数据库(redis在java项目中的使用)
-
java开发简历怎么写比较好(java简历项目描述)
-
java字符串查找某个字符(java查找字符串中指定字符)
-
javascript教程推荐(java零基础自学)
-
java获取时间戳精确到毫秒(java获取时间戳精确到微秒讲解)
-
jsonobject判断key是否存在某个key(java的foreach用法)
-
java获得当前日期时间(java获取当前时间的时分秒)