您的位置:首页 > 移动开发 > Android开发

Android 实现文件的下载

2011-06-02 11:20 309 查看
public void downFile(String url, String path, String fileName) throws IOException {
if (fileName == null || fileName == "")
this.FileName = url.substring(url.lastIndexOf("/") + 1);
else
this.FileName = fileName; // 取得文件名,如果输入新文件名,则使用新文件名
URL Url = new URL(url);
URLConnection conn = Url.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
this.fileSize = conn.getContentLength();// 根据响应获取文件大小
if (this.fileSize <= 0) { // 获取内容长度为0
throw new RuntimeException("无法获知文件大小 ");
}
if (is == null) { // 没有下载流
sendMsg(Down_ERROR);
throw new RuntimeException("无法获取文件");
}
FileOutputStream FOS = new FileOutputStream(path + this.FileName); // 创建写入文件内存流,通过此流向目标写文件
byte buf[] = new byte[1024];
downLoadFilePosition = 0;
int numread;
while ((numread = is.read(buf)) != -1) {
FOS.write(buf, 0, numread);
downLoadFilePosition += numread
}
try {
is.close();
}
catch (Exception ex) {
;
}
}


private Handler downloadHandler = new Handler() { // 用于接收消息,处理进度条

@Override
public void handleMessage(Message msg) { // 接收到的消息,并且对接收到的消息进行处理
if (!Thread.currentThread().isInterrupted()) {
switch (msg.what) {
case DOWN_START:
pb.setMax(fileSize); //设置开始长度
case DOWN_POSITION:
pb.setProgress(downLoadFilePosition); // 设置进度
break;
case DOWN_COMPLETE:
Toast.makeText(DownLoadFileTest.this, "下载完成!", 1).show(); // 完成提示
break;
case Down_ERROR:
String error = msg.getData().getString("下载出错!");
Toast.makeText(DownLoadFileTest.this, error, 1).show();
break;
}
}
super.handleMessage(msg);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: