2013-12-09 57 views
0

以下是我的FTPClient重試方法。它有一個錯誤。當初始連接成功時沒有問題。但是,如果2,3嘗試總是以NullPointerException結束。顯然連接是重試成功,但是當我嘗試列出遠程文件時,它會拋出異常。在java中的FTPClient(apache commons net)上重試連接

FTPClient ftpConnection(int in, FTPCon objGetFiles) { 

    FTPClient ftp = null; 

    if (in < RetryCount) { 
     try { 
      in = in + 1; 
      logger.debug("connecting ........."); 
      ftp = objGetFiles.connectToServer(FTPServer, FTPPort, FTPUser, FTPPasswd, RDir); 
      logger.debug("connected and the ftp object is "+ftp); 


     } catch (IOException ioe) { 

      logger.debug(ioe.toString()); 
      logger.debug("sleeping for " + (RetrySleep/1000) + " sec"); 
      try { 
       Thread.sleep(RetrySleep); 
       logger.debug("retrying connection"); 
       ftpConnection(in, objGetFiles); 

      } catch (InterruptedException iex) { 
       logger.debug(iex.toString()); 
      } 

     } 
    } else { 
     logger.debug("maximum retry exceed."); 
    } 

    return ftp; 

} 

DEBUG Starter - retrying connection 
    DEBUG Starter - connecting ......... 
    DEBUG FTPCon - connecting to server .... 
    DEBUG FTPCon - 230 Logged on 
    DEBUG FTPCon - changing working directory 
    DEBUG FTPCon - 250 CWD successful. "/tmp" is current directory. 
    DEBUG Starter - connected and the ftp object is  [email protected] 
    DEBUG Starter - java.lang.NullPointerException 

FTPFile n[] = ftp.listFiles(); 

以上是它拋出NullPointerException異常的地方。我相信它在重試方法中的錯誤(如初始連接始終正常工作),但至今沒有運氣

回答

0

您遞歸調用ftpConnection(),但你最終只返回頂級ftp變量自ftpConnection()每次調用具有自己ftp-variable。由於ftpConnection(in, objGetFiles)的結果未分配給變量,因此重試呼叫生成的對象FTPClient會立即丟失。

由於速戰速決做

 try { 
      Thread.sleep(RetrySleep); 
      logger.debug("retrying connection"); 
      ftp = ftpConnection(in, objGetFiles); 

     } catch (InterruptedException iex) { 
      logger.debug(iex.toString()); 
     } 

但是,如果使用遞歸是去,或者如果一個循環是對這類問題不是更好的正確方法我會考慮。

+0

謝謝指出。 – k119

相關問題