给定一个 url,我想将该 url 中的文件传输到特定的 ftp。 我有两个选择: 1)使用外部库(如apache common-io)我可以从url获取文件然后上传到ftp。 2) 打开两个套接字(到 url 和到 ftp)并简单地将文件从 url 传输到 ftp。
我是对的吗? 最好的方法是什么?
我正在使用 Spring 。
以下是我找到的一些相关链接:
How to download and save a file from Internet using Java? .
Here is the apache common-io library
编辑:
我正在处理 100-200M 的文件。
更新: 我选择先下载文件再上传。 我选择这样做是因为我预计下载文件时不会出现很多问题,但我预计将文件上传到 FTP 服务器时会出现问题。所以,我认为错误处理会更好。 缺少此解决方案的事实是我将临时文件存储在磁盘中。 如果我遇到一些问题,我会稍后更新。
最佳答案
1. 坦率地说,如果您正在使用开源,那么请利用外部库。
<强>2。不要重新发明轮子,您拥有可信赖的库供您使用,所以请使用它。
我还附加了我用来上传和下载歌曲的程序到ftp服务器
,使用apache的通用库
正在上传:
public void goforIt(){
FTPClient con = null;
try
{
con = new FTPClient();
con.connect("192.168.2.57");
if (con.login("Administrator", "KUjWbk"))
{
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
String data = "/sdcard/vivekm4a.m4a";
FileInputStream in = new FileInputStream(new File(data));
boolean result = con.storeFile("/vivekm4a.m4a", in);
in.close();
if (result) Log.v("upload result", "succeeded");
con.logout();
con.disconnect();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
下载:
public void goforIt(){
FTPClient con = null;
try
{
con = new FTPClient();
con.connect("192.168.2.57");
if (con.login("Administrator", "KUjWbk"))
{
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
String data = "/sdcard/vivekm4a.m4a";
OutputStream out = new FileOutputStream(new File(data));
boolean result = con.retrieveFile("vivekm4a.m4a", out);
out.close();
if (result) Log.v("download result", "succeeded");
con.logout();
con.disconnect();
}
}
catch (Exception e)
{
Log.v("download result","failed");
e.printStackTrace();
}
}
关于java - 如何使用java将文件从url传输到ftp?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11616611/