android 下载文件

public void downFile(String url,String filePath)
throws IOException {
url="http://10.85.185.116:8088/myIIS/Nobody.mp4";
filePath="/sdcard/NoBody.mp4";

URL Url = new URL(url);
URLConnection conn = Url.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
int fileSize = conn.getContentLength();// 根据响应获取文件大小
if (fileSize <= 0) { // 获取内容长度为0
throw new RuntimeException("无法获知文件大小 ");
}
if (is == null) { // 没有下载流
//sendMsg(Down_ERROR);
throw new RuntimeException("无法获取文件");
}
FileOutputStream FOS = new FileOutputStream(filePath); // 创建写入文件内存流,通过此流向目标写文件
byte buf[] = new byte[1024];
int downLoadFilePosition = 0;
int numread;
while ((numread = is.read(buf)) != -1) {
FOS.write(buf, 0, numread);
downLoadFilePosition += numread;
}

try {
is.close();
} catch (Exception ex) {}
}

你可能感兴趣的:(android)