How do I save a file downloaded with HttpClient into a specific folder

折月煮酒 提交于 2019-11-28 04:53:51
Eng.Fouad
InputStream is = entity.getContent();
String filePath = "sample.txt";
FileOutputStream fos = new FileOutputStream(new File(filePath));
int inByte;
while((inByte = is.read()) != -1)
     fos.write(inByte);
is.close();
fos.close();

EDIT:

you can also use BufferedOutputStream and BufferedInputStream for faster download:

BufferedInputStream bis = new BufferedInputStream(entity.getContent());
String filePath = "sample.txt";
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
int inByte;
while((inByte = bis.read()) != -1) bos.write(inByte);
bis.close();
bos.close();

Just for the record there are better (easier) ways of doing the same

File myFile = new File("mystuff.bin");

CloseableHttpClient client = HttpClients.createDefault();
try (CloseableHttpResponse response = client.execute(new HttpGet("http://host/stuff"))) {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try (FileOutputStream outstream = new FileOutputStream(myFile)) {
            entity.writeTo(outstream);
        }
    }
}

Or with the fluent API if one likes it better

Request.Get("http://host/stuff").execute().saveContent(myFile);

Here is a simple solution using IOUtils.copy():

File targetFile = new File("foo.pdf");

if (entity != null) {
    InputStream inputStream = entity.getContent();
    OutputStream outputStream = new FileOutputStream(targetFile);
    IOUtils.copy(inputStream, outputStream);
    outputStream.close();
}

return targetFile;

IOUtils.copy() is great because it handles buffering. However this solution is not very scalable:

  • you cannot specify target file name and directory
  • you might wish to store the files in a different way, e.g. in a database. Files aren't needed in this scenario.

Much more scalable solution involves two functions:

public void downloadFile(String url, OutputStream target) throws ClientProtocolException, IOException{
    //...
    if (entity != null) {
    //...
        InputStream inputStream = entity.getContent();
        IOUtils.copy(inputStream, target);
    }
}

And a helper method:

public void downloadAndSaveToFile(String url, File targetFile) {
    OutputStream outputStream = new FileOutputStream(targetFile);
    downloadFile(url, outputStream);
    outputStream.close();
}

If you are using Java 7+, you can use the native Files.copy(InputStream in, Path target, CopyOption... options), e.g.:

HttpEntity entity = response.getEntity();

try (InputStream inputStream = entity.getContent()) {
    Files.copy(inputStream, Paths.get(filePathString), StandardCopyOption.REPLACE_EXISTING);
}
Jeffrey Zhao

Open a FileOutputStream and save the bytes from inputStream to it.

Using dependency org.apache.httpcomponents:fluent-hc:

Request.Get(url).execute().saveContent(file);

Request is from org.apache.http.client.fluent.Request.

In my case I needed a stream, this is equally simple:

inputStream = Request.Get(url).execute().returnContent().asStream();

You can also use Apache http client fluent API

Executor executor = Executor.newInstance().auth(new HttpHost(host), "user", "password"); 
executor.execute(Request.Get(url.toURI()).connectTimeout(1000)).saveContent("C:/temp/somefile");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!