解决方法1:在Activity的onCreate()方法中加入如下代码:
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath() .build());
解决方法2: 在AndroidManifest.xml文件中加入如下标记:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
本来这个标记开是的时候就是加了,但是就是没用,后来试着把 <uses-sdk
android:minSdkVersion="4"/>这段标记加在上面两个标记前面就可以了。原先没该之前uses-sdk标记是这样的: <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
附加一份从互联网上下在txt文件的方法(该方法返回String字符串)
private URL url=null; public String download(String urlString) { StringBuffer sbBuffer=new StringBuffer(); String line=null; BufferedReader buffer=null; try { System.out.println("错"); //创建一个URL对象 url=new URL(urlString); //创建一个Http连接 HttpURLConnection urlConn=(HttpURLConnection)url.openConnection(); System.out.println("创建连接成功"); //使用IO流读取数据 buffer=new BufferedReader(new InputStreamReader(urlConn.getInputStream(),"GB2312")); // buffer=new BufferedReader(new InputStreamReader(urlConn.getInputStream())); System.out.println("使用IO流读取数据成功"); while ((line = buffer.readLine()) != null) { sbBuffer.append(line); } System.out.println("唔错"); } catch (Exception e) { // TODO: handle exception // System.out.println(e.getMessage()); // e. e.printStackTrace(); StackTraceElement[] stElements=e.getStackTrace(); for (StackTraceElement stackTraceElement : stElements) { String exclass = stackTraceElement.getClassName(); String method = stackTraceElement.getMethodName(); System.out.println(":" + "[类:" + exclass + "]调用" + method + "时在第" + stackTraceElement.getLineNumber() + "行代码处发生异常!异常类型:" + e.getClass().getName()); } } finally { try { buffer.close(); } catch (Exception e2) { // TODO: handle exception // System.out.println(); e2.printStackTrace(); } } return sbBuffer.toString(); }