import org.apache.commons.net.ftp.FTPClient;
import java.io.FileInputStream;
import java.io.IOException;
public class FtpFileUpload {
public static void main(String[] args) {
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("ftp.javacodegeeks.com");
client.login("username", "password");
// Create an InputStream of the file to be uploaded
String filename = "test.txt";
fis = new FileInputStream(filename);
// Store file on server and logout
client.storeFile(filename, fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
此博客展示了使用Java将文件上传到FTP服务器的代码。通过引入FTPClient类,连接到指定FTP服务器,登录后将本地文件以输入流形式上传,最后登出并关闭连接,同时处理了可能出现的IO异常。
1305

被折叠的 条评论
为什么被折叠?



