当前位置: 首页 > 面试题库 >

如何将使用HttpClient下载的文件保存到特定文件夹中

孔鸿云
2023-03-14
问题内容

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

我有以下代码,如何将其存储为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();

编辑:

您还可以使用BufferedOutputStream和BufferedInputStream来加快下载速度:

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


 类似资料:
  • 在shell脚本中,我想从某个URL下载一个文件,并将其保存到特定的文件夹中。使用命令将文件下载到特定文件夹时应使用的特定CLI标志是什么,或者如何获得该结果?

  • 问题内容: 我一直试图将纯文本文件保存到Android上Google云端硬盘中的特定文件夹中。 到目前为止,使用Google云端硬盘上的文档和快速入门指南,我已经可以做一些正确的事情,首先,我可以创建一个纯文本文件: 我已经能够使用以下命令在Google云端硬盘的基本目录中创建一个新文件夹: 我还能够通过以下方式列出用户的Google云端硬盘帐户中的所有文件夹: 但是,我对如何将文本文件保存到Go

  • 我正在使用node的开发者工具包将图像上传到AWS S3: 这是可行的,但我如何才能使图像上传到一个特定的文件夹中的桶?

  • 我正试图上传一个文件到我的谷歌硬盘,下面的代码工作。如何指定要上载到哪个文件夹,即驱动器--shared with me--csvFolder

  • 问题内容: 基本上,我想做的是允许用户自己制作folder,然后转到activity包含的button来启动camera。 从这里我希望能够启动camera并将camera图像保存到新创建的文件夹中。 我在将camera图像保存到新创建的文件夹的最后一部分时遇到麻烦。 这是我的Code: 从这里我过渡到此活动: public class Press extends Activity { 请告诉我如