Android FTPClient - retrieveFileStream()始终返回null

时间:2011-11-24 13:12:49

标签: android ftp-client apache-commons-net

我是Android的新手。我正在尝试使用Apache Commons FTPClient将文件从ftp服务器下载到SD卡。行 InputStream input = client.retrieveFileStream(“/”+ fileName); 始终返回null。但该文件位于Ftp位置。请帮助我知道错误在哪里。

我在清单中设置了以下权限; 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();
    }

}

感谢您的时间和兴趣。 Ananth。

3 个答案:

答案 0 :(得分:6)

AFAIK。您可以通过调用completePendingCommand()并验证传输确实成功来完成文件传输。即你需要在fos.clos()下面添加调用函数。

fos.close();
client.completePendingCommand()

您也可以考虑这一点,根据FTPClient.retrieveFileStream()的API,该方法在无法打开数据连接时返回null,在这种情况下您应该检查回复代码(例如getReplyCode(),getReplyString() ,getReplyStrings())看看它失败的原因。

答案 1 :(得分:0)

          File file = new File(Environment.getExternalStorageDirectory() + "/pdf");
        if(!file.exists())

           file.mkdir(); //directory is created;
            try {
                ftp = new FTPClient();
                ftp.connect("yours ftp URL",21);//don't write ftp://

                try {
                    int reply = ftp.getReplyCode();
                  if (!FTPReply.isPositiveCompletion(reply)) {
                    throw new Exception("Connect failed: " + ftp.getReplyString());
                    }
                    if (!ftp.login("username","password")) {
                      throw new Exception("Login failed: " + ftp.getReplyString());
                    }
                    try {
                        ftp.enterLocalPassiveMode();
                        if (!ftp.setFileType(FTP.BINARY_FILE_TYPE)) {
//                          Log.e(TAG, "Setting binary file type failed.");
                        }

                        transferFile(ftp);
                    } catch(Exception e) {
//                      handleThrowable(e);
                    } finally {
                        if (!ftp.logout()) {
//                          Log.e(TAG, "Logout failed.");
                        }
                    }
                } catch(Exception e) {
//                  handleThrowable(e);
                } finally {
                    ftp.disconnect();
                }
            } catch(Exception e) {
//              handleThrowable(e);
            }


    }


       private void transferFile(FTPClient ftp) throws Exception {
        long fileSize=0;
        fileSize = getFileSize(ftp, "nag.pdf");
        Log.v("async","fileSize"+fileSize);
        if(!(fileSize==0)){
            InputStream is = retrieveFileStream(ftp,  "nag.pdf");
            downloadFile(is,  fileSize);
            is.close();
            }
            else


                 //nosuch files

        if (!ftp.completePendingCommand()) {
            throw new Exception("Pending command failed: " + ftp.getReplyString());
        }
    }

    private InputStream retrieveFileStream(FTPClient ftp, String filePath)
    throws Exception {
        InputStream is = ftp.retrieveFileStream(filePath);
        int reply = ftp.getReplyCode();
        if (is == null
                || (!FTPReply.isPositivePreliminary(reply)
                        && !FTPReply.isPositiveCompletion(reply))) {
            throw new Exception(ftp.getReplyString());
        }
        return is;
    }

    private byte[] downloadFile(InputStream is, long fileSize)
    throws Exception {
    outputStream os = newFileOutputStream(Environment.getExternalStorageDirectory()
                + "/pdf/nag.pdf");  
        byte[] buffer = new byte[(int) fileSize];
        int readCount;
        while( (readCount = is.read(buffer)) > 0) {
            os.write(buffer, 0, readCount);
        }
        Log.i("tag", "buffer = " + buffer);
        return buffer; // <-- Here is your file's contents !!!
    }

    private long getFileSize(FTPClient ftp, String filePath) throws Exception {
        long fileSize = 0;
        FTPFile[] files = ftp.listFiles(filePath);
        if (files.length == 1 && files[0].isFile()) {
            fileSize = files[0].getSize();
        }
        Log.i("tag", "File size = " + fileSize);
        return fileSize;
    }

}

答案 2 :(得分:0)

在解决了这个问题并花费了数小时之后,我发现当 FileSize 时,Android Apache retrieveFile()retrieveFileStream有时无法很好地工作太大。

确保将正确的 TypeFile 设置为 BinaryFile

mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);

也永远不会忘记为下载命令传递LocalPassiveMode

mFTPClient.enterLocalPassiveMode();