2009-02-03 27 views
8

我使用的是org.apache.commons.net.ftp.FTPClient,看到的行爲就是......很困惑。java中的FTPClient類的問題

下面的方法打算通過一個FTPFile列表,讀入它們,然後做一些內容。這一切都工作。什麼不是(真的)工作是FTPClient對象執行以下操作...

1) Properly retrieves and stores the FIRST file in the list 
2) List item evaluates to NULL for x number of successive iterations of the loop (x varies on successive attempts 
3) manages to retrieve exactly 1 more file in the list 
4) reports that it is null for exactly 1 more file in the list 
5) hangs indefinitely, reporting no further activity. 

public static String mergeXMLFiles(List<FTPFile> files, String rootElementNodeName, FTPClient ftp){ 
     String ret = null; 
     String fileAsString = null; 
     //InputStream inStream; 
     int c; 

     if(files == null || rootElementNodeName == null) 
      return null; 
     try { 
      System.out.println("GETTING " + files.size() + " files"); 
      for (FTPFile file : files) { 
       fileAsString = ""; 
       InputStream inStream = ftp.retrieveFileStream(file.getName()); 

       if(inStream == null){ 
        System.out.println("FtpUtil.mergeXMLFiles() couldn't initialize inStream for file:" + file.getName()); 

        continue;//THIS IS THE PART THAT I SEE FOR files [1 - arbitrary number (usually around 20)] and then 1 more time for [x + 2] after [x + 1] passes successfully. 
       } 
       while((c = inStream.read()) != -1){ 

        fileAsString += Character.valueOf((char)c); 
       } 
       inStream.close(); 


       System.out.println("FILE:" + file.getName() + "\n" + fileAsString); 
      } 


     } catch (Exception e) { 
      System.out.println("FtpUtil.mergeXMLFiles() failed:" + e); 
     } 
     return ret; 
    } 

有沒有人看過類似的東西?我是新來的FTPClient,我做錯了嗎?

+0

您可以編輯您的帖子如此,而不是使用代碼視圖列表項改爲使用列表項的規定簡碼?使它更具可讀性:) – Kezzer 2009-02-03 16:25:47

回答

14

據爲FTPClient.retrieveFileStream()的API,當它不能打開數據連接,在這種情況下,你應該檢查答覆代碼(例如getReplyCode()getReplyString()getReplyStrings()),看看它爲什麼失敗的方法返回null。另外,您還打算通過致電completePendingCommand()並確認傳輸確實成功完成文件傳輸。

+2

completePendingComand()!!!!!你是一個紳士和一個學者 我正在檢查replyCode(在前面的方法中,我做所有的連接垃圾),這一切工作正常。我忽略了指定completePendingCommand重要性的文檔。 非常感謝。 – 2009-02-03 16:33:12

2

當我添加它的工作確定了「檢索」命令後:

 int response = client.getReply(); 
     if (response != FTPReply.CLOSING_DATA_CONNECTION){ 
      //TODO 
     }