我是Android编程的新手。我需要从ftp服务器下载视频,jpgs和pdf到我的Android设备。
这是我在线程中的下载代码
MyFTPClient ftpclient=null;
ftpclient = new MyFTPClient();
status = ftpclient.ftpConnect("xxx.xxx.xxx.xxx", "username", "password", 21);
if (status == true) {
Log.d(TAG, "Connection Success");
FTPFile[] filelist= ftpclient.ftpPrintFilesList("/httpdocs/");
for(int i=0;i<filelist.length;i++){
if(filelist[i].getType()==1)
{
File myFile = new File("/storage/sdcard0/App/"+filelist[i].getName());
if(!myFile.exists()){
File folder=new File("/storage/sdcard0/App/"+filelist[i].getName());
folder.mkdir();
}
}
else if(filelist[i].getType()==0)
{
ftpclient.ftpDownload("/httpdocs/"+filelist[i].getName(), "/storage/sdcard0/App/"+filelist[i].getName());
}
}
else {
Log.d(TAG, "Connection failed");
}
这是我的FTP客户端类
public boolean ftpConnect(String host, String username,
String password, int port)
{
try {
mFTPClient = new FTPClient();
mFTPClient.connect(host, port);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
boolean status = mFTPClient.login(username, password);
mFTPClient.setFileType(FTP.ASCII_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch(Exception e) {
Log.d(TAG, "Error: could not connect to host " + host+"Cause: "+e.getCause() );
}
return false;
}
public FTPFile[] ftpPrintFilesList(String dir_path)
{
try {
FTPFile[] ftpFiles = mFTPClient.listFiles(dir_path);
int length = ftpFiles.length;
for (int i = 0; i < length; i++) {
String name = ftpFiles[i].getName();
boolean isFile = ftpFiles[i].isFile();
if (isFile) {
Log.i(TAG, "File : " + name);
}
else {
Log.i(TAG, "Directory : " + name);
}
}
return ftpFiles;
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
public boolean ftpDownload(String srcFilePath, String desFilePath)
{
boolean status = false;
try {
FileOutputStream desFileStream = new FileOutputStream(desFilePath);;
status = mFTPClient.retrieveFile(srcFilePath, desFileStream);
desFileStream.flush();
desFileStream.close();
return status;
} catch (Exception e) {
Log.d(TAG, "download failed");
}
return status;
}
这些代码会下载文件,但是当我想打开一些pdf或视频时,我会收到错误“打开文档时出错”
如何正确处理下载代码?可能是错误的原因是什么?
P.S:视频文件为100-200 MB,pdf文件为1-5 MB
答案 0 :(得分:1)
为什么要在登录方法中设置此内容? mFTPClient.setFileType(FTP.ASCII_FILE_TYPE);最后应该保留为二进制文件......