android 如何从tomcat服务器上下载文件

如题所述

//下载
private InputStream FileDownload(String url_str) throws Exception{

URL url = new URL(url_str);
// 创建连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(3000);
conn.setConnectTimeout(3000);
conn.connect();

// 获取文件大小
length = conn.getContentLength();
// 创建输入流
InputStream is = conn.getInputStream();

return is;
}
//保存
private void FileSave(String filename,InputStream is,int length) throws Exception{

File file = new File(mSavePath);
// 判断文件目录是否存在
if (!file.exists())
{
file.mkdir();
}
File apkFile = new File(mSavePath, filename);
FileOutputStream fos = new FileOutputStream(apkFile);
int count = 0;
// 缓存
byte buf[] = new byte[1024];
// 写入到文件中
do
{
int numread = is.read(buf);
count += numread;
// 计算进度条位置
progress = (int) (((float) count / length) * 100);
// 更新进度
mHandler.sendEmptyMessage(DOWNLOAD);
if (numread <= 0)
{
// 下载完成
mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
break;
}
// 写入文件
fos.write(buf, 0, numread);
} while (!cancelUpdate);// 点击取消就停止下载.
fos.close();
}

/**
* 安装APK文件
*/
private void installApk()
{
File apkfile = new File(mSavePath, mHashMap.get("name"));
if (!apkfile.exists())
{
return;
}
// 通过Intent安装APK文件
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
mContext.startActivity(i);
}
温馨提示:内容为网友见解,仅供参考
第1个回答  推荐于2016-06-01
//下载
private InputStream FileDownload(String url_str) throws Exception{

URL url = new URL(url_str);
// 创建连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(3000);
conn.setConnectTimeout(3000);
conn.connect();

// 获取文件大小
length = conn.getContentLength();
// 创建输入流
InputStream is = conn.getInputStream();

return is;
}
//保存
private void FileSave(String filename,InputStream is,int length) throws Exception{

File file = new File(mSavePath);
// 判断文件目录是否存在
if (!file.exists())
{
file.mkdir();
}
File apkFile = new File(mSavePath, filename);
FileOutputStream fos = new FileOutputStream(apkFile);
int count = 0;
// 缓存
byte buf[] = new byte[1024];
// 写入到文件中
do
{
int numread = is.read(buf);
count += numread;
// 计算进度条位置
progress = (int) (((float) count / length) * 100);
// 更新进度
mHandler.sendEmptyMessage(DOWNLOAD);
if (numread <= 0)
{
// 下载完成
mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
break;
}
// 写入文件
fos.write(buf, 0, numread);
} while (!cancelUpdate);// 点击取消就停止下载.
fos.close();
}

/**
* 安装APK文件
*/
private void installApk()
{
File apkfile = new File(mSavePath, mHashMap.get("name"));
if (!apkfile.exists())
{
return;
}
// 通过Intent安装APK文件
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
mContext.startActivity(i);
}
相似回答