2010-07-29 60 views
2

我正在使用httpclient从网页下载图片,我试图将它们保存到磁盘,但没有多少运气。我使用下面的代码来获取图像,但不知道需要未来做什么真正得到它的磁盘,取数据将是对JPG或PNG图像路径...感谢如何将图像存储到Java中的磁盘?

HttpContext localContext = new BasicHttpContext(); 
     localContext.setAttribute(ClientContext.COOKIE_STORE,HttpClientFetch.emptyCookieStore); 

     HttpGet httpget = new HttpGet(pPage.imageSrc); 
     HttpResponse response; 
     response = httpClient.execute(httpget, localContext); 

     Header[] headers = response.getAllHeaders(); 
     for(Header h: headers) { 
      logger.info("HEADERS: "+h.getName()+ " value: "+h.getValue()); 
     } 

     HttpEntity entity = response.getEntity(); 


     Header contentType = response.getFirstHeader("Content-Type"); 

     byte[] tmpFileData; 

     if (entity != null) { 
      InputStream instream = entity.getContent(); 
      int l; 
      tmpFileData = new byte[2048]; 
      while ((l = instream.read(tmpFileData)) != -1) { 
      } 
     } 

tmpFileData现在应该保存来自网站的jpg的字节。

+1

会不会使用fileOutputStream.write(byte [])工作吗? – samitgaur 2010-07-29 20:31:51

回答

3
if (entity != null) { 
    InputStream instream = entity.getContent(); 
    OutputStream outstream = new FileOutputStream("YourFile"); 
    org.apache.commons.io.IOUtils.copy(instream, outstream); 
} 
+0

工作!谢谢:) – James 2010-07-29 20:47:20

+0

使用此示例,Java显示错误,因为YourFile不存在。为什么会发生这种情况,我认为这个脚本试图创建这个文件,而不是从它读取。 – eLRuLL 2013-03-22 16:29:32

1

看一看FileOutputStream及其write方法。

FileOutputStream out = new FileOutputStream("outputfilename"); 
out.write(tmpFileData); 
1

更好地利用阿帕奇百科全书-10,那么你可以一个InputStream的只是复制到一个OutputStream的(FileOutputStream中你的情况)。