如何将使用HttpClient下载的文件保存到特定文件夹中 [英] How do I save a file downloaded with HttpClient into a specific folder
本文介绍了如何将使用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();
编辑:
您还可以使用 BufferedOutputStream 和 BufferedInputStream 可以更快地下载:
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屋!
查看全文