android中如何从网上下载文件源码
String FileName=null;
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) { // 没有下载流
throw new RuntimeException("无法获取文件");
}
//String finema = Environment.getExternalStorageDirectory()+"/ww.jpg";
//Log.e("path",finema);
FileOutputStream FOS = new FileOutputStream(fileName); // 创建写入文件内存流,通过此流向目标写文件
byte buf[] = new byte[1024]; //开辟缓存,保存文件
int numread;
while ((numread = is.read(buf)) != -1) {
FOS.write(buf, 0, numread); //将文件逐 byte写入
}
try {
is.close();
} catch (Exception e) {
}
}
补充说明:1、path处,我最早是直接用的"/sdcard/",但是一直报错java.io.FileNotFoundException:....Read-Only File System,不知为什么。后改为path=Environment.getExternalStorageDirectory()+"/ww.jpg";成功 。
2、联网要在Mainfest中加权限:<uses-permission android:name="android.permission.INTERNET"></uses-permission>
对SDCARD的操作:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>