从 URLConnection 读取二进制文件
我正在尝试从 URLConnection 读取二进制文件。当我用文本文件测试它时,它似乎工作正常,但对于二进制文件则不然。当文件发送出去时,我在服务器上使用以下 mime 类型:
application/octet-stream
但到目前为止似乎没有任何效果。这是我用来接收文件的代码:
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();
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:
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我就是这样做的
This is how I do it,
如果您尝试读取二进制流,则不应将
InputStream
包装在任何类型的Reader
中。使用InputStream.read(byte[], int, int)
方法将数据读入字节数组缓冲区。然后从缓冲区写入FileOutputStream
。您当前读取/写入文件的方式将使用平台的默认字符编码将其转换为“字符”并返回字节。这很容易破坏二进制数据。
(有一个字符集 (LATIN-1),它在字节和
char
值空间的子集之间提供 1 对 1 无损映射。然而,即使映射有效,这也是一个坏主意。您将把二进制数据从byte[]
翻译/复制到char[]
并再次返回......这在这种情况下没有任何效果。)If you are trying to read a binary stream, you should NOT wrap the
InputStream
in aReader
of any kind. Read the data into a byte array buffer using theInputStream.read(byte[], int, int)
method. Then write from the buffer to aFileOutputStream
.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
char
value-space. However this is a bad idea even when the mapping works. You will be translating / copying the binary data frombyte[]
tochar[]
and back again ... which achieves nothing in this context.)