package com.android.filedemo;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int i = download(
" http://android.d.cn/rm/2/1971/3577/?http://a.downandroid.com/android/new/game1/72/108972/advanced_task_manager_2.apk",
MainActivity.this.getFilesDir().getParent() + "/files/" + "file.apk");
System.out.println(i);
}
/**
* 从网上下载
* @param url 下载路径
* @param outputFile 创建本地保存流的文件
* @return
* @return 下载失败返回1(比如没有网络等情况)下载成功返回0
*/
public int download(String urlPsth, String savePath) {
int result = 0;
File outputFile = new File(savePath);
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;
}
}
下载apk到临时文件夹中
最新推荐文章于 2023-01-09 21:40:05 发布