2017-02-21 58 views
1

我试图下载一个主机提供的一些图像。这是我使用的方法:下载Piktogramms时太大的文件

public static void downloadImage(String imageLink, File f) throws IOException 
{ 
    URL url = new URL(imageLink); 
    byte[] buffer = new byte[1024]; 
    BufferedInputStream in = new BufferedInputStream(url.openStream(), buffer.length); 
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f), buffer.length); 

    while (in.read(buffer) > 0) 
     out.write(buffer); 
    out.flush(); 
    out.close(); 
    in.close(); 
} 

但是,文件变得太大了。我认为5MB的80x60 JPG太多了。

这可能是什么原因造成的?

+1

请你帮个忙,并使用库这一点。我最喜欢的流副本是Apache Commons IOUtils(https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/IOUtils.html#copy(java.io。 InputStream,%20java.io.OutputStream)) –

+1

不客气;感谢您的快速接受。 – GhostCat

+1

和旁注;我同意托马斯的观点:除非这是一个“教育练习” - 你最好用一些图书馆来做到这一点。 – GhostCat

回答

1

你在这里做的错了:read()返回真正被读取的字节数;因此您必须将您的缓冲区阵列中的那个数字写入您的输出流。

您的代码正在破坏您的输出;并简单地写出一个缓冲区数组......主要由0组成!

而是做这样的事情:

int bytesRead; 
while ((bytesRead = in.read(buffer)) > 0) { 
    byte outBuffer[] = new byte[bytesRead]; 
    ... then use arraycopy to move bytesRead bytes 
    out.write(outBuffer); 
} 

(这意味着为灵感让你去,更喜欢伪不是真正的代码)

+0

谢谢。我会确保记住这个事实 –