James
James

Reputation: 15475

How do I store an image to disk in Java?

I'm using httpclient to download images from a webpage and I'm trying to save them to disk but not having much luck. I'm using the code below to fetch the image but not sure what needs to be done next to actually get it to disk, the fetch would be on a JPG or a PNG image path... thanks

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 should now hold the bytes of the jpg from the website.

Upvotes: 2

Views: 1154

Answers (3)

Taylor Leese
Taylor Leese

Reputation: 52310

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

Upvotes: 3

Jeff
Jeff

Reputation: 21892

Have a look at FileOutputStream and its write method.

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

Upvotes: 1

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16142

Better use Apache commons-io, then you can just copy one InputStream to one OutputStream (FileOutputStream in your case).

Upvotes: 1

Related Questions