本示例演示如何将文件上传到FTP服务器。
package org.nhooo.example.commons.net; import org.apache.commons.net.ftp.FTPClient; import java.io.IOException; import java.io.InputStream; public class FTPUploadDemo { public static void main(String[] args) { FTPClient client = new FTPClient(); String filename = "data.txt"; // 从资源文件夹中读取文件。 ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try (InputStream is = classLoader.getResourceAsStream(filename)) { client.connect("ftp.example.org"); client.login("admin", "admin123**"); // 将文件存储到服务器 client.storeFile(filename, is); client.logout(); } catch (IOException e) { e.printStackTrace(); } finally { try { client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } }
Maven依赖
<!-- http://repo1.maven.org/maven2/commons-net/commons-net/3.6/commons-net-3.6.jar --> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.6</version> </dependency>