在android中如何从服务器上下载文件 并写入到 sdcard上去

来源:互联网 发布:mysql的update触发器 编辑:程序博客网 时间:2024/06/05 07:36
public class DownloadFileTask {

/**
* @param path 获得apk的路径地址
* @param filepath 存储apk的路径地址
* @return 返回file类型的文件
* @throws MException 

*文件的下载比较固定 即 获得网络连接 获得输入流 从输入流开始读数据  如果要写入到sd卡中 需要 建立输出流
*利用输出流 写入到 sd卡中去  这些都是java的基础知识 
*/
public static File getdFile(String path,String filepath) throws Exception{
URL url = new URL(path);//
HttpURLConnection connection = (HttpURLConnection) url.openConnection();//从网络获得链接
connection.setRequestMethod("GET");//获得
connection.setConnectTimeout(5000);//设置超时时间为5s

if(connection.getResponseCode()==200)//检测是否正常返回数据请求 详情参照http协议
{
InputStream is = connection.getInputStream();//获得输入流
File file  = new File(filepath);//新建一个file文件
FileOutputStream fos = new FileOutputStream(file);//对应文件建立输出流
byte[] buffer = new byte[1024];//新建缓存  用来存储 从网络读取数据 再写入文件
int len = 0;
while((len=is.read(buffer)) != -1){//当没有读到最后的时候 
fos.write(buffer, 0, len);//将缓存中的存储的文件流秀娥问file文件
}
fos.flush();//将缓存中的写入file
fos.close();
is.close();//将输入流 输出流关闭

return file;
}
return null;

}

}