本文介绍了使用 Java 上传到 FTP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是想知道是否有一种简单方法可以将小文件上传到 ftp 服务器.我已经查看了 Apache Commons Net 库,但老实说这似乎相当复杂.有没有更简单的方法可以把小文件上传到ftp?
I was just wondering if there was a simple way I could upload a small file to a ftp server. I've checked out Apache Commons Net library but that seems quite complicated to be honest. Is there any simpler way to upload a small file to ftp?
最终使用了 Apache Commons Net Library,并不太难.
Ended up using the Apache Commons Net Library, wasn't too hard.
推荐答案
来自这个链接:使用 URLConnection 类上传文件到 FTP 服务器.无需外部库.
From this link: Upload files to FTP server using URLConnection class. No external library necessary.
String ftpUrl = "ftp://%s:%s@%s/%s;type=i";
String host = "www.myserver.com";
String user = "tom";
String pass = "secret";
String filePath = "E:/Work/Project.zip";
String uploadPath = "/MyProjects/archive/Project.zip";
ftpUrl = String.format(ftpUrl, user, pass, host, uploadPath);
System.out.println("Upload URL: " + ftpUrl);
try {
URL url = new URL(ftpUrl);
URLConnection conn = url.openConnection();
OutputStream outputStream = conn.getOutputStream();
FileInputStream inputStream = new FileInputStream(filePath);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
System.out.println("File uploaded");
} catch (IOException ex) {
ex.printStackTrace();
}
这篇关于使用 Java 上传到 FTP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!