android 实现下载文件
2010-11-05 00:56:50 来源:WEB开发网核心提示:Java代码/*** 从网上下载*@param url 下载路径*@param outputFile 创建本地保存流的文件*@return* @return 下载失败返回1(比如没有网络等情况)下载成功返回0*/public static int downloadFile(String urlPsth, File ou
Java代码
/**
* 从网上下载
*@param url 下载路径
*@param outputFile 创建本地保存流的文件
*@return
* @return 下载失败返回1(比如没有网络等情况)下载成功返回0
*/
public static int downloadFile(String urlPsth, File outputFile) {
int result=0;
try {
URL url = new URL(urlPsth);
HttpURLConnection conn =(HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(outputFile);
byte[] bt = new byte[1024];
int i = 0;
while ((i = is.read(bt)) > 0) {
fos.write(bt, 0, i);
}
fos.flush();
fos.close();
is.close();
}else {
result=1;
}
} catch (FileNotFoundException e) {
result=1;
} catch (IOException e) {
result=1;
}
return result;
}
[]
更多精彩
赞助商链接