import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.Environment;
public class HttpDownloader {
private URL url = null;
/**
* SDCARD路径
*/
private String SDPATH = Environment.getExternalStorageDirectory() + "/";
/**
* 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文件当中的内容
*/
public String downloadText(String urlStr) {
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader buffer = null;
try {
url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while ((line = buffer.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
buffer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}
/**
* 该函数返回整数 -1:代表下载文件出错 0:代表下载文件成功 1:代表文件已经存在
*/
public int downloadFile(String urlStr, String filePath, String fileName) {
InputStream inputStream = null;
try {
File file = new File(SDPATH + filePath + fileName);
if (file.exists()) {//判断SD卡上的文件夹是否存在
return 1;
} else {
url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
inputStream = urlConn.getInputStream();
File resultFile = write2SDFromInput(filePath, fileName, inputStream);
if (resultFile == null) {
return -1;
}
}
} catch (Exception e) {
e.printStackTrace();
return -1;
} finally {
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return 0;
}
/**
* 将一个InputStream里面的数据写入到SD卡中
*/
public File write2SDFromInput(String filePath, String fileName, InputStream input){
File file = null;
OutputStream output = null;
try{
new File(SDPATH + filePath).mkdirs();//在SD卡上创建目录
file = new File(SDPATH + filePath + fileName);
file.createNewFile();//在SD卡上创建文件
output = new FileOutputStream(file);
byte[] buffer = new byte[5 * 1024];
while((input.read(buffer)) != -1){
output.write(buffer);
}
output.flush();
} catch(Exception e){
e.printStackTrace();
} finally{
try{
output.close();
} catch(Exception e){
e.printStackTrace();
}
}
return file;
}
}