Skip to content

Instantly share code, notes, and snippets.

@huantt
Created July 3, 2016 14:22
Show Gist options
  • Save huantt/6de0cabb00e54ad237d66277b179546f to your computer and use it in GitHub Desktop.
Save huantt/6de0cabb00e54ad237d66277b179546f to your computer and use it in GitHub Desktop.
Download file sử dụng stream
package com.phongbm.filemanager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Huan on 7/3/2016.
*/
public class Downloader {
private InputStream is;
private FileOutputStream fos;
public Downloader() {
}
public void dowload(String link, String des) {
try {
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
is = connection.getInputStream();
File file = new File(des);
if (file.exists()) {
file.delete();
}
file.createNewFile();
fos = new FileOutputStream(file);
byte[] b = new byte[1024];
int leng = is.read(b);
while (leng != -1) {
fos.write(b, 0, leng);
leng = is.read(b);
}
is.close();
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment