java – 从URLConnection读取二进制文件 - 代码日志

java – 从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();
这是我做的,

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();
http://stackoverflow.com/questions/3221979/reading-binary-file-from-urlconnection

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:java – 从URLConnection读取二进制文件