簡體   English   中英

如何在Java中將映像存儲到磁盤?

[英]How do I store an image to disk in Java?

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

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

看一下FileOutputStream及其write方法。

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

最好使用Apache commons-io,然后可以將一個InputStream復制到一個OutputStream(在您的情況下為FileOutputStream)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM