【发布时间】:2014-08-21 05:39:22
【问题描述】:
你好我很好奇如何在java中下载数据,所以我看了几个方法决定使用BufferedInputStream。
现在当我下载时,我以 1024 字节突发下载文件,每次下载 1kb 我将临时数组连接到主数据数组。tH
我用这个concat方法:
public static byte[] concat(byte[] data, byte[] bytes) {
byte[] result = Arrays.copyOf(data, data.length + bytes.length);
System.arraycopy(bytes, 0, result, data.length, bytes.length);
return result;
}
这是我的下载过程:
URL target = new URL ("http://freshhdwall.com/wp-content/uploads/2014/08/Image-Art-Gallery.jpg");
URLConnection t = target.openConnection();
t.setRequestProperty("User-Agent", "NING/1.0");
t.connect();
BufferedInputStream stream = new BufferedInputStream(t.getInputStream());
final byte[] bytes = new byte[1024];
int count;
byte[] data = new byte[0];
while ( (count = stream.read(bytes, 0, bytes.length)) != -1) {
System.out.println(count);
data = concat(data, bytes);
}
现在下载后,我使用ByteArrayInputStream将字节数组转换为BufferedImage:
InputStream s = new ByteArrayInputStream(data);
BufferedImage m = ImageIO.read(s);
然后我显示结果:
JFrame j = new JFrame();
j.add(new JLabel(new ImageIcon(m)));
j.pack();
j.setVisible(true);
现在结果图像如下所示:
(来源:gyazo.com)
如您所见,下载时图像看起来已损坏,缺少字节。 这是真实的图像:
img http://freshhdwall.com/wp-content/uploads/2014/08/Image-Art-Gallery.jpg
我做错了什么,它显示这样的图像?
【问题讨论】:
-
你的代码很适合我
标签: java image networking