2011-09-14 199 views
2

我在android上使用apache FTPClient。我想從ftp服務器下載一個文件。但是我想在下載之前檢查它是否存在於服務器上。我怎樣才能檢查這個?如何檢查FTP服務器上是否存在文件?

感謝,

我的代碼:

public static boolean getFile(String serverName, String userName, 
     String password, String serverFilePath, String localFilePath) 
     throws Exception { 

    FTPClient ftp = new FTPClient(); 
    try { 
     ftp.connect(serverName); 
     int reply = ftp.getReplyCode(); 

     if (!FTPReply.isPositiveCompletion(reply)) { 
      ftp.disconnect(); 
      return false; 
     } 
    } catch (IOException e) { 
     if (ftp.isConnected()) { 
      try { 
       ftp.disconnect(); 
      } catch (IOException f) { 
       throw e; 
      } 
     } 
     throw e; 
    } catch (Exception e) { 
     throw e; 
    } 

    try { 
     if (!ftp.login(userName, password)) { 
      ftp.logout(); 
     }   
     ftp.setFileType(FTPClient.BINARY_FILE_TYPE); 
     ftp.enterLocalPassiveMode(); 

     OutputStream output; 

     output = new FileOutputStream(localFilePath);   
     ftp.retrieveFile(serverFilePath, output); 
     output.close(); 

     ftp.noop(); // check that control connection is working OK 
     ftp.logout(); 
     return true; 

    } catch (FTPConnectionClosedException e) { 
     throw e; 
    } catch (IOException e) { 
     throw e; 
    } catch (Exception e) { 
     throw e; 
    } finally { 
     if (ftp.isConnected()) { 
      try { 
       ftp.disconnect(); 
      } catch (IOException f) { 
       throw f; 
      } 
     } 

    } 

} 

回答

0

當客戶端發送RETR和服務器返回錯誤代碼550響應,你可以相當肯定的是,文件不存在,或者你不有權獲取它...由於FTP規範有點鬆散,你可能會假設550-559範圍內的任何錯誤,這表明永久文件系統錯誤。

2
String[] files = ftp.listnames(); 

看文件,如果所需的文件名是包括...

-2
InputStream inputStream = ftpClient.retrieveFileStream(filePath); 
if (inputStream == null || ftpClient.getReplyCode() == 550) { 
// it means that file doesn't exist. 
} 


or 

FTPFile[] mFileArray = ftp.listFiles(); 
// you can check if array contains needed file 
+0

必須加上completePendingCommand(),以防止問題遵循FTP命令。 – Florian

1

假設ftpClientorg.apache.commons.net.ftp.FTPClient一個實例:

public boolean fileExists(String fileName) throws IOException 
{ 
    String[] files = ftpClient.listNames(); 

    return Arrays.asList(files).contains(fileName); 
} 
相關問題