2012-02-27 10 views
13

私の携帯電話でsdcardにファイルをダウンロードしようとしています。 Android 2.1,2.2,3.3では、すべてが意図どおりに動作しますが、Android 4.0(testenはエミュレータと私のGalaxy Nexus)ではFileNotFoundExceptionがスローされます。AndroidバージョンのFileNotFoundException> 2.3

スタックトレース:

02-27 21:49:06.733: W/System.err(27648): java.io.FileNotFoundException: http://www.wdr.de/wdrlive/media/wdr5.m3u 
02-27 21:49:06.733: W/System.err(27648): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177) 
02-27 21:49:06.733: W/System.err(27648): at de.arvidg.test.StartActivity$9.run(StartActivity.java:833) 
02-27 21:49:06.733: W/System.err(27648): at java.lang.Thread.run(Thread.java:856) 


ファイルのダウンロードのための私の方法:だから、答えること

downloadFile("http://www.wdr.de/wdrlive/media/wdr5.m3u"); 

    public void downloadFile(final String fileUrl) { 
     new Thread(new Runnable() { 

      @Override 
      public void run() { 
       try { 

        URL url = new URL(fileUrl); 

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 

        urlConnection.setRequestMethod("GET"); 
        urlConnection.setDoOutput(true); 

        urlConnection.connect(); 

//     File cacheDir = appContext.getExternalCacheDir(); 
//     File file = new File("/mnt/sdcard", "/cacheFile.ext"); 
        File SDCardRoot = Environment.getExternalStorageDirectory(); 
        File file = new File(SDCardRoot,"/cacheFile.ext"); 

        if(!file.exists()) file.createNewFile(); 

        FileOutputStream fileOutput = new FileOutputStream(file); 

        InputStream inputStream = urlConnection.getInputStream(); 

        int totalSize = urlConnection.getContentLength(); 
        int downloadedSize = 0; 

        byte[] buffer = new byte[1024]; 
        int bufferLength = 0; 

        while ((bufferLength = inputStream.read(buffer)) > 0) { 
         fileOutput.write(buffer, 0, bufferLength); 
         downloadedSize += bufferLength; 
         Log.d(TAG, "downloadedSize = " + downloadedSize + " | totalSize = " + totalSize); 
//      updateProgress(downloadedSize, totalSize); 

        } 
        fileOutput.close(); 

      } catch (MalformedURLException e) { 
        e.printStackTrace(); 
      } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 

     }).start(); 
    } 
+2

問題の原因は何もありませんが、キャッシュファイルには絶対ファイル名を使用しないでください。代わりにこれを試してください: 'File file = new File(SDCardRoot、" cacheFile.ext ");'( "/"がないことに注意してください)。 –

+0

ありがとう、ありがとう。それは確かに行います。誰でもエラーがどこから来たのか考えてみてください。 – Leandros

+0

レスポンスコードを確認するurlConnection.getResponseCode();プロセス入力ストリームの前に – yorkw

答えて

37

シンプル削除PFNの@#アンドロイド-devのにurlConnection.setDoOutput(true);

おかげ

+3

+1シンプルでクリーンなソリューションです。 – yorkw

+0

素敵な答え+1短くて便利私の問題を解決してくれてありがとう。 –

+0

+1、 'setDoInput()'はどうですか? – NullPointer

8

を元の質問、サーバーからエラーメッセージが表示された後、getInputStream()にアクセスしようとすると、が表示されます。レスポンスコードが400以上の場合、getInputStream()を呼び出すとこのエラーが発生します。この場合、代わりにgetErrorStream()をチェックする必要があります。私の答えhereを参照してください。

関連する問題