我知道如何使用ftp4j上传文件,但是我想使用同样的方法从FTP下载文件,我希望看到:
下面是我用来上传的代码:
file_destination = new File(filDir +"/"+fileName); // where fileDir + filename = sdcard/document/file.txt
private void uploadImage() {
// TODO Auto-generated method stub
file_destination_string = file_destination.toString();
upload_file = new File(file_destination_string);
uploadFile(upload_file);
}
private void uploadFile(File f) {
// TODO Auto-generated method stub
client = new FTPClient();
try {
client.connect(FTP_HOST,21); //where HOST is ip address of server
client.login(FTP_USER, FTP_PASS); // FTP user / password
client.setType(FTPClient.TYPE_BINARY);
client.changeDirectory(FTP_DIR); //where FTP_DIR = /httpdocs/folder/
client.upload(f, new MyTransferListener());
} catch (Exception e) {
Toast.makeText(getBaseContext(), "FTP Failed: "+e, Toast.LENGTH_SHORT).show();
System.out.println("e1..."+e);
e.printStackTrace();
try {
client.disconnect(true);
Log.e("MYAPP", "exception", e);
System.out.println("e2...");
} catch (Exception e2) {
System.out.println("e3...");
e2.printStackTrace();
}
}
}
public class MyTransferListener implements FTPDataTransferListener {
public void started() {
Toast.makeText(getBaseContext(), " Upload Started ...", Toast.LENGTH_SHORT).show();
}
public void transferred(int length) {
Toast.makeText(getBaseContext(), " transferred ..." + length, Toast.LENGTH_SHORT).show();
}
public void completed() {
Toast.makeText(getBaseContext(), " completed ...", Toast.LENGTH_SHORT).show();
}
public void aborted() {
Toast.makeText(getBaseContext()," transfer aborted, please try again...", Toast.LENGTH_SHORT).show();
}
public void failed() {
Toast.makeText(getBaseContext()," failed..", Toast.LENGTH_SHORT).show();
}
}如何下载文件?
发布于 2016-07-21 06:09:15
有一个下载方法可用。
您只需使用client.download("myfile.txt", new java.io.File("d:/myfile.txt"));,就可以将"myfile.txt“下载到"D:\myfile.txt”。
对于android来说,整个过程略有不同。如果要将文件存储在定义的文件夹中(例如,在sdcard上),可以这样使用:
client.download("myfile.txt", new java.io.File("/sdcard/myfile.txt"));
如果要将其下载到应用程序默认数据目录,则可以使用context.getExternalFilesDir()方法。如果将null作为参数传递,这将返回应用程序外部存储上的私有目录的根目录。
此外,在这里引用AndroidDevelopers:
从
KITKAT开始,不需要任何权限来读取或写入返回的路径;调用应用程序总是可以访问它。这仅适用于为调用应用程序的包名生成的路径。要访问属于其他包的路径,需要WRITE_EXTERNAL_STORAGE和/或READ_EXTERNAL_STORAGE。
因此,您不需要这两个权限来访问您自己的应用程序文件。
最后,这段代码应该下载一个文件,并在应用程序默认目录中创建一个新文件:
client.download("myfile.txt", new java.io.File(context.getExternalFilesDir(null), "myfile.txt"));
发布于 2016-07-20 13:19:20
我在他们的API中看到了downlod方法。
void download(java.lang.String remoteFileName, java.io.File localFile)
This method downloads a remote file from the server to a local file.下面是API链接- http://www.sauronsoftware.it/projects/ftp4j/api/it/sauronsoftware/ftp4j/FTPClient.html
https://stackoverflow.com/questions/38482381
复制相似问题