Created
July 3, 2016 14:22
-
-
Save huantt/6de0cabb00e54ad237d66277b179546f to your computer and use it in GitHub Desktop.
Download file sử dụng stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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