【发布时间】:2013-04-14 14:10:03
【问题描述】:
我需要一个非常简单的函数,允许我通过 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 时它会出错!
我肯定被卡住了。一些 cmets 会非常有用!
【问题讨论】:
-
欢迎来到 Stackoverflow!无需为您的标题添加标签,有一个标签系统。请阅读meta.stackexchange.com/q/19190/147072 了解更多信息。此外,您无需在末尾添加“谢谢”或您的名字,每个人都感谢您的帮助,并且您的名字显示在您创建的每个问题和答案的右下角的字符表中。