用 Java 将下载的二进制文件写入磁盘

发布于 2024-08-06 00:23:49 字数 915 浏览 4 评论 0原文

我有一个软件,允许在 javascript 文件(.js)中编写附加组件,允许使用 Java 函数(我不知道这是否常见,我以前从未在 javascript 文件中看到过 java 调用)

我需要下载一个来自网络服务器的二进制文件并将其写入硬盘。我尝试了以下代码:

baseencoder = new org.apache.commons.codec.binary.Base64();
url = new java.net.URL("https://server/file.tgz");

urlConnect = url.openConnection();
urlConnect.setDoInput(true);
urlConnect.setDoOutput(true);
urlConnect.setRequestProperty("authorization","Basic "+ java.lang.String(baseencoder.encodeBase64(java.lang.String( username + ":" + password ).getBytes())));
urlConnect.setRequestProperty("content-type","application/x-www-form-urlencoded");

is = new java.io.DataInputStream(urlConnect.getInputStream());
fstream = new FileWriter("C:\\tmp\\test.tgz");
out = new BufferedWriter(fstream);
while((data = is.read()) != -1){
    out.write(data);
}

out.close();
is.close();

生成的文件不再是有效的 gzip 存档。如果我犯了一个巨大的错误,我很抱歉,但我不是程序员,对 Java 不太了解。

I have a software that allow to write add-on in javascript files (.js) that allow to use Java function (I don't know if this is common, I never saw java call in javascript file before)

I need to download a binary file from a webserver and write it to the hard drive. I tried the following code:

baseencoder = new org.apache.commons.codec.binary.Base64();
url = new java.net.URL("https://server/file.tgz");

urlConnect = url.openConnection();
urlConnect.setDoInput(true);
urlConnect.setDoOutput(true);
urlConnect.setRequestProperty("authorization","Basic "+ java.lang.String(baseencoder.encodeBase64(java.lang.String( username + ":" + password ).getBytes())));
urlConnect.setRequestProperty("content-type","application/x-www-form-urlencoded");

is = new java.io.DataInputStream(urlConnect.getInputStream());
fstream = new FileWriter("C:\\tmp\\test.tgz");
out = new BufferedWriter(fstream);
while((data = is.read()) != -1){
    out.write(data);
}

out.close();
is.close();

The resulting file is no longer a valid gzip archive. I'm sorry if I did a huge error but I'm not a programmer and don't know Java too much.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

贵在坚持 2024-08-13 00:23:49

不要使用 FileWriter- 尝试将数据转换为文本。

只需使用FileOutputStream

byte[] buffer = new byte[8 * 1024];

InputStream input = urlConnect.getInputStream();
try {
  OutputStream output = new FileOutputStream(filename);
  try {
    int bytesRead;
    while ((bytesRead = input.read(buffer)) != -1) {
      output.write(buffer, 0, bytesRead);
    }
  } finally {
    output.close();
  }
} finally {
  input.close();
}

Don't use a FileWriter - that's trying to convert the data into text.

Just use FileOutputStream.

byte[] buffer = new byte[8 * 1024];

InputStream input = urlConnect.getInputStream();
try {
  OutputStream output = new FileOutputStream(filename);
  try {
    int bytesRead;
    while ((bytesRead = input.read(buffer)) != -1) {
      output.write(buffer, 0, bytesRead);
    }
  } finally {
    output.close();
  }
} finally {
  input.close();
}
酒绊 2024-08-13 00:23:49

我知道这个问题已经得到解答,但更简单的方法是使用 Apache Commons IO 的 IOUtils.copy() 方法,该方法可以将 InputStream 完全复制到 输出流

I know this question is already answered, but a simpler approach is to use Apache Commons IO's IOUtils.copy() method, which can fully copy an InputStream to an OutputStream.

耳根太软 2024-08-13 00:23:49

DataInputStream 用于读取 Java 原语,而不是通用数据。

它也是多余的,因为 urlConnect.getInputStream(); 已经返回一个InputStream,并且所有InputStreams都支持read()。

is = urlConnect.getInputStream();

PS 这假设 isbis 是同一个变量。否则,您将在循环中读取错误的流。

DataInputStream is meant for reading Java primitives, not for generic data.

It's also redundant, as urlConnect.getInputStream(); already returns an InputStream, and all InputStreams support read().

is = urlConnect.getInputStream();

P.S. This is assuming is and bis are the same variable. Otherwise, you're reading the wrong stream in the loop.

美男兮 2024-08-13 00:23:49

刚刚阅读的 LimitInputStream 听起来就像它所做的正是您正在做的事情,缓冲输入流以提高效率。

Just read about LimitInputStream sounds like it does exactly what you are doing, buffering the input stream for greater efficiency.

心凉怎暖 2024-08-13 00:23:49

您甚至可以使用 NIO FileChannel#transferFrom 方法。

            URL website = new URL(urlToDownload);

            try (ReadableByteChannel rbc = Channels.newChannel(website.openStream());
                    FileOutputStream fos = new FileOutputStream(filePath);) {
                fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            }

参考link1 链接2

You can even use NIO FileChannel#transferFrom method.

            URL website = new URL(urlToDownload);

            try (ReadableByteChannel rbc = Channels.newChannel(website.openStream());
                    FileOutputStream fos = new FileOutputStream(filePath);) {
                fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            }

Reference link1, link2

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文