我是 Android 新手。我正在尝试使用 Apache Commons FTPClient 从 ftp 服务器将文件下载到 sdcard。 InputStream input = client.retrieveFileStream("/"+ fileName); 行始终返回 null。但该文件位于 Ftp 位置。请帮助我知道错误在哪里。
我在 list 中设置了以下权限; android:name="android.permission.INTERNET"和 android:name="android.permission.WRITE_EXTERNAL_STORAGE"
我的代码
private static void downLoad(){
FTPClient client = new FTPClient();
FileOutputStream fos = null;
try {
client.connect("ftp.doamin.com");
client.login("8888", "8888");
String filePath = "/mnt/sdcard/download/CheckboxHTML.txt" ;
String fileName = "CheckboxHTML.txt";
fos = new FileOutputStream(filePath);
InputStream input = client.retrieveFileStream("/" + fileName);
byte[] data = new byte[1024];
int count = input.read(data);
while ((count = input.read(data)) != -1) {
fos.write(data, 0, count);
}
fos.close();
if(!client.completePendingCommand()) {
client.logout();
client.disconnect();
System.err.println("File transfer failed.");
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
感谢您的时间和兴趣。阿南斯。
最佳答案
据我所知。您应该通过调用 completePendingCommand() 并验证传输确实成功来完成文件传输。即您需要在 fos.clos() 下面添加调用函数。
fos.close();
client.completePendingCommand()
你也可以考虑这个,根据FTPClient.retrieveFileStream()的API,该方法在无法打开数据连接时返回null,此时你应该检查回复代码(例如getReplyCode(), getReplyString() , getReplyStrings()) 看看失败的原因。
关于Android FTPClient - retrieveFileStream() 总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8257639/