2013-04-14 97 views
6

我需要一個非常簡單的函數,它允許我通過FTP讀取文件的前1k個字節。我想在MATLAB中使用它來讀取第一行,並根據一些參數,只下載我最終真正需要的文件。我在網上發現了一些例子,不幸的是不工作。在這裏,我提出了示例代碼,我試圖下載一個單獨的文件(我使用的是Apache庫)。讀取文件的第一個字節

FTPClient client = new FTPClient(); 
    FileOutputStream fos = null; 

    try { 
     client.connect("data.site.org"); 

     // filename to be downloaded. 
     String filename = "filename.Z"; 
     fos = new FileOutputStream(filename); 

     // Download file from FTP server 
     InputStream stream = client.retrieveFileStream("/pub/obs/2008/021/ab120210.08d.Z"); 
     byte[] b = new byte[1024]; 
     stream.read(b); 
     fos.write(b); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      if (fos != null) { 
       fos.close(); 
      } 
      client.disconnect(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

錯誤在流中返回空。我知道我以錯誤的方式傳遞文件夾名稱,但我無法理解我該怎麼做。我嘗試了很多方法。

我也與URL的Java類嘗試作爲:

URL url; 

    url = new URL("ftp://data.site.org/pub/obs/2008/021/ab120210.08d.Z"); 

    URLConnection con = url.openConnection(); 
    BufferedInputStream in = 
      new BufferedInputStream(con.getInputStream()); 
    FileOutputStream out = 
      new FileOutputStream("C:\\filename.Z"); 

    int i; 
    byte[] bytesIn = new byte[1024]; 
    if ((i = in.read(bytesIn)) >= 0) { 
     out.write(bytesIn); 
    } 
    out.close(); 
    in.close(); 

,但它給當我關閉InputStream的一個錯誤!

我絕對卡住了。有些評論會非常有用!

+0

歡迎計算器!沒有必要爲標題添加標籤,這裏有一個標籤系統。請閱讀http://meta.stackexchange.com/q/19190/147072瞭解更多信息。此外,最後不需要添加「謝謝」或您的姓名,每個人都感謝您的幫助,並且您的姓名會顯示在您創建的每個問題和答案的右下角的角色表中。 – Patrick

回答

1

試試這個測試

InputStream is = new URL("ftp://test:[email protected]/bookstore.xml").openStream(); 
    byte[] a = new byte[1000]; 
    int n = is.read(a); 
    is.close(); 
    System.out.println(new String(a, 0, n)); 

它肯定工程

+0

嗨,代碼只有在整個文件被下載時纔有效。我添加了兩行,用於將數據存儲在本地驅動器的輸出文件中。當我從MATLAB運行代碼時,它會下載文件(我可以在文件夾中看到它,並且可以打開它),但它會卡在輸入連接關閉的行(is.close())。如果我刪除它的作品。問題是我不知道如何管理連接,我想避免無緣無故地打開端口。 最後一件事。如果我下載所有文件,則is.close()工作正常!這是讓我瘋狂的東西:)。 – user2279697

-1

我不明白爲什麼這是行不通的。我發現這個link他們使用Apache庫每次讀取4096字節。我讀了第一個1024字節,並且它最終工作,唯一的是如果使用completePendingCommand(),程序永遠保存。因此我刪除了它,一切正常。

0

根據我的經驗,當您從ftpClient.retrieveFileStream獲取的流中讀取字節時,對於第一次運行,不保證您將字節緩衝區填滿。然而,無論是你應該閱讀此基礎上的stream.read(b);用循環包圍返回值,或者使用高級庫,填補了1024字節長度[]緩衝區:

InputStream stream = null; 
try { 
    // Download file from FTP server 
    stream = client.retrieveFileStream("/pub/obs/2008/021/ab120210.08d.Z"); 
    byte[] b = new byte[1024]; 
    IOUtils.read(stream, b); // will call periodically stream.read() until it fills up your buffer or reaches end-of-file 
    fos.write(b); 

} catch (IOException e) { 
    e.printStackTrace(); 
} finally { 
    IOUtils.closeQuietly(inputStream); 
}