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

如何在Java中将映像存储到磁盘?,java,image,Java,Image,我正在使用httpclient从网页下载图像,并试图将它们保存到磁盘,但运气不太好。我正在使用下面的代码获取图像,但不确定下一步需要做什么才能真正将其获取到磁盘,获取将位于JPG或PNG图像路径上。。。谢谢 HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE,HttpClientFetch.emptyCookieStore);

我正在使用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的字节。

看看它的
写入方法

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

最好使用Apache commons io,然后您可以将一个InputStream复制到一个OutputStream(在您的例子中是FileOutputStream)。

使用FileOutputStream.write(byte[])不起作用吗?在这个示例中,Java显示了一个错误,因为您的文件不存在。为什么会发生这种情况,我假设这个脚本试图创建这个文件,而不是从中读取。
if (entity != null) { 
    InputStream instream = entity.getContent();
    OutputStream outstream = new FileOutputStream("YourFile");
    org.apache.commons.io.IOUtils.copy(instream, outstream);
}