繁体   English   中英

读取文件的第一个字节

[英]Read first bytes of a file

我需要一个非常简单的函数,允许我通过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时它会出错!

我肯定卡住了。 一些评论会非常有用!

试试这个测试

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

它确实有效

根据我从ftpClient.retrieveFileStream获取的流中读取字节的经验,对于第一次运行,不保证您填充了字节缓冲区。 但是,您应该读取stream.read(b);的返回值stream.read(b); 用基于它的循环包围或使用高级库来填充1024长度byte []缓冲区:

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);
}

我无法理解为什么它不起作用。 我找到了这个链接 ,他们使用Apache库每次读取4096个字节。 我读了前1024个字节并且它最终起作用,唯一的事情是如果使用了completePendingCommand(),程序将永远保留。 因此我删除了它,一切正常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM