如何将使用 HttpClient 下载的文件保存到特定文件夹中 [英] How do I save a file downloaded with HttpClient into a specific folder

查看:47
本文介绍了如何将使用 HttpClient 下载的文件保存到特定文件夹中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 HttpClient 下载 PDF 文件.我能够获取文件,但我不确定如何将字节转换为 PDF 并将其存储在系统上的某个位置

I am trying to download a PDF file with HttpClient. I am able to get the file but i am not sure how to convert the bytes into a a PDF and store it somewhere on the system

我有以下代码,如何将其存储为 PDF?

I have the following code, How can I store it as a PDF?

 public ???? getFile(String url) throws ClientProtocolException, IOException{

            HttpGet httpget = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpget);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                long len = entity.getContentLength();
                InputStream inputStream = entity.getContent();
                // How do I write it?
            }

            return null;
        }

推荐答案

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();

<小时>

您还可以使用 BufferedOutputStreamBufferedInputStream 以加快下载速度:

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();

这篇关于如何将使用 HttpClient 下载的文件保存到特定文件夹中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆