2012-06-09 24 views
26

Tôi đang cố tải xuống tệp PDF bằng HttpClient. Tôi có thể tải tệp nhưng tôi không chắc chắn cách chuyển đổi byte thành PDF và lưu trữ nó ở đâu đó trên hệ thốngLàm cách nào để lưu tệp được tải xuống bằng HttpClient vào một thư mục cụ thể

Tôi có mã sau đây, Làm cách nào để lưu trữ dưới dạng 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; 
     } 

Trả lời

33
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:

bạn cũng có thể sử dụng BufferedOutputStreamBufferedInputStream để tải về nhanh hơn:

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

HttpClient tối ưu hóa hoạt động đọc nội bộ. Không cần phải sử dụng một lớp đệm khác – oleg

+0

Tôi không thể ghi trực tiếp vào đường dẫn tệp đó, tôi đã phải sử dụng 'Tệp tệp = tệp mới (context.getExternalFilesDir (Environment.DIRECTORY_DOWNLOADS), "filename.jpg"); 'cho ghi vào bộ nhớ ngoài để các ứng dụng khác có thể xem ứng dụng của tôi – Aaron

1

Mở FileOutputStream và lưu byte từ inputStream vào đó.

+0

Có gì khó hiểu tôi là bạn có một FileOutputStream đã được mở trong phương pháp downloadAndSaveToFile, nhưng khi tôi tạo ra các đối tượng tập tin với đường dẫn đầy đủ, tôi nhận được một 'File không tồn tại' lỗi ... bạn có thể hiển thị mã của chúng tôi sẽ lấy tập tin này đã được tải xuống và lưu nó vào một thư mục cụ thể? –

+0

Tôi xin lỗi, tôi đã có lỗi đánh máy trong đường dẫn của mình. Khi nó quay ra, tôi có thể chỉ định đối tượng tập tin với đường dẫn mong muốn đầy đủ khi đường dẫn là một đường dẫn VALID. :-) –

21

Đây là một giải pháp đơn giản sử dụng 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() thật tuyệt vì nó xử lý bộ đệm. Tuy nhiên giải pháp này không phải là rất khả năng mở rộng:

  • bạn không thể chỉ định tên tập tin và thư mục đích
  • bạn có thể muốn để lưu trữ các tập tin theo một cách khác, ví dụ trong cơ sở dữ liệu. Không cần tệp trong trường hợp này.

nhiều khả năng mở rộng hơn giải pháp liên quan đến hai chức năng:

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

Và một phương pháp helper:

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

Điều này sẽ truyền tệp hoặc giữ toàn bộ tệp trong bộ nhớ và sau đó lưu vào đĩa? –

26

Chỉ cần cho các hồ sơ có tốt hơn (dễ dàng hơn) cách để làm cùng

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

Hoặc với API thông thạo nếu bạn thích nó tốt hơn

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

Gói phù thủy tôi cần phải nhập cho 'Request.Get (" http: // host/stuff ") .execute(). SaveContent (myFile)' – badera

+0

Trong Maven bạn cần tạo phẩm 'org.apache.httpcomponents: fluent- hc' - gói Java là 'org.apache.http.client.fluent.Request' –

Các vấn đề liên quan