2013-04-14 101 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); 
}