Java 从 URLConnection 读取二进制文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3221979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:31:27  来源:igfitidea点击:

Reading binary file from URLConnection

javahttpdownloadurlconnection

提问by Luke

I'm trying to read a binary file from a URLConnection. When I test it with a text file it seems to work fine but for binary files it doesn't. I'm using the following mime-type on the server when the file is send out:

我正在尝试从 URLConnection 读取二进制文件。当我用文本文件测试它时,它似乎工作正常,但对于二进制文件则不然。发送文件时,我在服务器上使用以下 MIME 类型:

application/octet-stream

But so far nothing seems to work. This is the code that I use to receive the file:

但到目前为止似乎没有任何效果。这是我用来接收文件的代码:

file = File.createTempFile( "tempfile", ".bin");
file.deleteOnExit();

URL url = new URL( "http://somedomain.com/image.gif" );

URLConnection connection = url.openConnection();

BufferedReader input = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );

Writer writer = new OutputStreamWriter( new FileOutputStream( file ) );

int c;

while( ( c = input.read() ) != -1 ) {

   writer.write( (char)c );
}

writer.close();

input.close();

采纳答案by ZZ Coder

This is how I do it,

我就是这样做的

input = connection.getInputStream();
byte[] buffer = new byte[4096];
int n;

OutputStream output = new FileOutputStream( file );
while ((n = input.read(buffer)) != -1) 
{
    output.write(buffer, 0, n);
}
output.close();

回答by Stephen C

If you are trying to read a binary stream, you should NOT wrap the InputStreamin a Readerof any kind. Read the data into a byte array buffer using the InputStream.read(byte[], int, int)method. Then write from the buffer to a FileOutputStream.

如果您尝试读取二进制流,则不应将InputStreama包装在Reader任何类型中。使用该InputStream.read(byte[], int, int)方法将数据读入字节数组缓冲区。然后从缓冲区写入FileOutputStream.

The way you are currently reading/writing the file will convert it into "characters" and back to bytes using your platform's default character encoding. This is liable to mangle binary data.

您当前读取/写入文件的方式将使用平台的默认字符编码将其转换为“字符”并返回到字节。这很容易损坏二进制数据。

(There is a charset (LATIN-1) that provides a 1-to-1 lossless mapping between bytes and a subset of the charvalue-space. However this is a bad idea even when the mapping works. You will be translating / copying the binary data from byte[]to char[]and back again ... which achieves nothing in this context.)

(有一个字符集(LATIN-1)提供字节和char值空间子集之间的一对一无损映射。但是,即使映射有效,这也是一个坏主意。您将翻译/复制二进制数据从byte[]char[]和返回......在这种情况下什么也没有实现。)