读取文件的第一个字节

use*_*697 6 java ftp matlab

我需要一个非常简单的函数,允许我通过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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

错误在流中返回为空.我知道我以错误的方式传递文件夹名称,但我无法理解我该怎么做.我试过很多方面.

我也尝试过使用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();
Run Code Online (Sandbox Code Playgroud)

但是当我关闭InputStream时它会出错!

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

Evg*_*eev 1

尝试这个测试

    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));
Run Code Online (Sandbox Code Playgroud)

它绝对有效