我正在尝试使用此代码从FTP服务器检索文件。
private class FtpTask extends AsyncTask<Void, Void, Long> {
protected Long doInBackground(Void... args) {
FTPClient FtpClient = new FTPClient();
int reply;
try {
FtpClient.connect(ftpServer);
FtpClient.login(ftpUser, ftpPass);
reply = FtpClient.getReplyCode();
if (FTPReply.isPositiveCompletion(reply)) {
String remoteFileName = "ACPlus.ZIP";
String localFile = context.getFilesDir() + "/ACPLUS.ZIP";
// Delete local file first
File file = new File(localFile);
if(file.exists()) {
file.delete();
}
FtpClient.changeWorkingDirectory("/" + ftpFolder);
FtpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
FtpClient.enterLocalPassiveMode();
OutputStream outputStream = null;
boolean success = false;
try {
outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
success = FtpClient.retrieveFile(remoteFileName, outputStream);
reply = FtpClient.getReplyCode();
}
finally {
if (outputStream != null) {
outputStream.close();
}
}
bConnected = success;
}
else
{
bConnected = false;
}
}
catch (Exception ex) {
return null;
}
return null;
}
protected void onPostExecute(Long result) {
super.onPostExecute(result);
if (bConnected == true) {
// Extract local file
File file = new File(context.getFilesDir() + "/ACPLUS.ZIP");
if(file.exists()) {
}
}
else
{
AlertDialog.Builder msg = new AlertDialog.Builder(context);
msg.setTitle("Error");
msg.setMessage("Connection could not be established!");
msg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
});
AlertDialog dialog = msg.create();
dialog.show();
}
}
作为测试,我逐步执行了代码,然后进入
// Delete local file first
File file = new File(localFile);
if(file.exists()) {
file.delete();
}
我停止了调试,所以我知道该文件已被删除。然后,我再次开始逐步执行。这次它错过了file.delete();
,因为if语句为false
,因此证明删除文件已成功完成。
但是,当我继续浏览时,到达行success = FtpClient.retrieveFile(remoteFileName, outputStream);
时,success
的值为false
,这意味着我的onPostExecute
没有走通过正确的代码。
但是,当再次调试它时,它确实通过了if语句并删除了本地文件,表明实际上已经下载了,尽管success = false
提出了其他建议。
我误会了什么,还是这是通常的行为?