gpt4 book ai didi

java - 读取文件的第一个字节

转载 作者:搜寻专家 更新时间:2023-10-31 08:03:51 24 4
gpt4 key购买 nike

我需要一个非常简单的函数,允许我通过 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));

绝对有效

关于java - 读取文件的第一个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15999980/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com