gpt4 book ai didi

java - 从 URLConnection 读取二进制文件

转载 作者:IT老高 更新时间:2023-10-28 20:50:02 24 4
gpt4 key购买 nike

我正在尝试从 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();

关于java - 从 URLConnection 读取二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3221979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com