从 URLConnection 读取二进制文件 [英] Reading binary file from URLConnection
本文介绍了从 URLConnection 读取二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从 URLConnection 读取二进制文件.当我用文本文件测试它时,它似乎工作正常,但对于二进制文件则不然.发送文件时,我在服务器上使用以下 MIME 类型:
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();
推荐答案
我就是这样做的,
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();
这篇关于从 URLConnection 读取二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文