如何用Java将映像存储到磁盘?

时间:2010-07-29 20:25:17

标签: java image

我正在使用httpclient从网页下载图片,我正在尝试将它们保存到磁盘但没有太多运气。我正在使用下面的代码来获取图像,但不确定接下来需要做什么才能实际将它放到磁盘上,获取将在JPG或PNG图像路径上...谢谢

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的字节。

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

查看FileOutputStream及其write方法。

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

答案 2 :(得分:1)

更好地使用Apache commons-io,然后您可以将一个InputStream复制到一个OutputStream(在您的情况下为FileOutputStream)。