1.必须要开子线程来操作耗时操作,android.os.NetworkOnMainThreadException
new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { updateFile = Environment.getExternalStorageDirectory() + "/3530.jpg"; //downloadUpdateFile("http://image.anzimall.com/3530/3530_K21D_app_V2.3_2015050528.bin", updateFile); downloadUpdateFile("http://img1.cache.netease.com/catchpic/F/FC/FCC085159B92C5EE4FDDB9618166051E.jpg", updateFile); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); //android.os.NetworkOnMainThreadException System.out.println(e.toString()+""); } } }).start();
2.抛出异常之后一定要打印异常,看看异常的具体信息。System.out.println(e.toString()+"");
public static long downloadUpdateFile(String down_url, String file)
throws Exception {
int downloadCount = 0;// 已经下载好的大小
InputStream inputStream;
OutputStream outputStream;
URL url = new URL(down_url);
HttpURLConnection httpurlconnection = (HttpURLConnection) url
.openConnection();
httpurlconnection.setConnectTimeout(5000);
httpurlconnection.setReadTimeout(5000);
// 获取下载文件的size
//totalSize = httpURLConnection.getContentLength();
if (httpurlconnection.getResponseCode() == 404) {
throw new Exception("fail!");
// 这个地方应该加一个下载失败的处理,但是,因为我们在外面加了一个try---catch,已经处理了Exception,
// 所以不用处理
}
inputStream = httpurlconnection.getInputStream();
File file_ok = new File(file);
outputStream = new FileOutputStream(file_ok);// 文件存在则覆盖掉
byte buffer[] = new byte[1024];
int readsize = 0;
while ((readsize = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, readsize);
downloadCount += readsize;// 时时获取下载到的大小
}
if (httpurlconnection != null) {
httpurlconnection.disconnect();
}
inputStream.close();
outputStream.close();
return downloadCount;
}