此错误是因为Android不能在主线程中访问网络导致,可将访问网络代码另启线程运行:
Runnable r = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
URL url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
String path = "file";
String fileName = fileNa + "." + fileEx;
OutputStream output = null;
/*获取SD卡路径*/
String SDCard = "/mnt/sdcard/HTTPget"; //Environment.getExternalStorageDirectory()+"";
System.out.println(SDCard);
String pathName = SDCard + "/" + path + "/" + fileName; //文件保存路径
File file = new File(pathName);
InputStream input = conn.getInputStream();
if(file.exists())
{
System.out.println("file exits");
return;
}
else
{
String dir = SDCard + "/" + path;
new File(dir).mkdirs(); //创建文件夹
file.createNewFile(); //创建文件
output = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int len;
while((len = input.read(buffer)) != -1)
{
output.write(buffer, 0, len);
}
output.flush();
}
} catch (MalformedURLException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
};
new Thread(r).start();
}