下载txt文件使app崩溃

时间:2012-02-03 15:29:31

标签: java android

我尝试使用以下方法从互联网上下载文件:

try { 
    URL url = new URL("http://sites.google.com/site/androidersite/text.txt");
    BufferedReader in =new BufferedReader(new InputStreamReader(url.openStream()));
    String str;
    while ((str = in.readLine()) != null) {  newline character(s)
    }  
    in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
} 

我还更新了Android Manifest并添加以下行:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

并且此行中的应用程序崩溃:

BufferedReader in =new BufferedReader(new InputStreamReader(url.openStream()));

并弹出一个写有Source not found

的日志文件

2 个答案:

答案 0 :(得分:2)

此代码是否在主应用程序线程上运行?您正在测试哪个版本的Android?如果它在主(UI)线程上,那就不好了。它可能会抛出“主线程上的网络”异常,因为它们不鼓励你这样做:)

您能否从崩溃中提供一些实际的logcat输出,或者可能为正在执行的代码提供更多上下文?

答案 1 :(得分:2)

可能相关

http://www.javahotchocolate.com/tutorials/android.html#notfound http://stackoverflow.com/questions/4720593/source-not-found-error-in-android

           /* Open a connection to that URL. */
           URLConnection ucon = url.openConnection();

           /*
            * Define InputStreams to read from the URLConnection.
            */
           InputStream is = ucon.getInputStream();
           BufferedInputStream bis = new BufferedInputStream(is);

点击此处查看http://www.helloandroid.com/tutorials/how-download-fileimage-url-your-device