2011-09-14 18 views
2

私はアンドロイドで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(); 

見た目ファイル任意のファイル名が含まれている場合... ftpClientを想定し

-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

org.apache.commons.net.ftp.FTPClientのインスタンスである:

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

    return Arrays.asList(files).contains(fileName); 
} 
関連する問題