下载文件时出现Java.io.FileNotFoundException

时间:2014-12-10 12:46:33

标签: java android

我无法弄清楚这里的问题是什么,它曾经工作但不再存在。我正在尝试从网址下载文件。好像我没有正确创建文件。

            static String PATH = Environment.getExternalStorageDirectory() + "/Android/data/com.xxxx.xxxx/";
            url = new URL("http://xxxxxxx.xxx/file.apk");
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(false);
            c.connect();


            File file = new File(PATH);
            File outputFile = new File(file, "update"+separated[1]+".apk");

            //it crashes at this point

            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();


 java.io.FileNotFoundException: /storage/emulated/0/Android/data/com.xxxxx.xxx/update150.apk: open failed: ENOENT (No such file or directory)
    at libcore.io.IoBridge.open(IoBridge.java:409)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:73)
    at com.sanisidrolsa.appterris.GcmIntentService.onHandleIntent(GcmIntentService.java:67)
    at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.os.HandlerThread.run(HandlerThread.java:61)
 Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
    at libcore.io.Posix.open(Native Method)
    at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
    at libcore.io.IoBridge.open(IoBridge.java:393)
    ... 7 more

1 个答案:

答案 0 :(得分:0)

在Android 4.0中,您无法在主线程上发出网络或HTTP请求,否则会出现ANR(应用程序无响应)错误。

您需要将HTTP请求放入新线程中。因为高版本的Android OS认为异步I / O请求(例如网络或数据库)更好。

Android OS中有几种关于异步操作的技术。

也许this对您有所帮助。