0

我對Android非常陌生,並且需要製作一個應用程序,該應用程序需要下載並緩存使用的url中的jpg文件。OutputStream問題... OutofBoundsException

我已經從多個引用(和我自己的修修補補)這麼遠到這一點:

public class download_image extends AsyncTask<String, Void, String> { 
    int count; 
    @Override 
    protected String doInBackground(String... urls) { 
     try { 
      String root = getFilesDir().toString(); 
      URL imgurl = new URL(urls[0]); // Form a URL object from string. 
      URLConnection c = imgurl.openConnection(); //Open connection. 
      int length_of_file = c.getContentLength();  // Get size of target jpg 
      Log.v("Background Response","Length fo target img = "+length_of_file); 
      InputStream i = new BufferedInputStream(imgurl.openStream(),length_of_file); 

      //Make target image file... 
      final File image = new File(getApplicationContext().getCacheDir().toString(),"image.jpg"); 

      OutputStream o = new FileOutputStream(image); 
      byte data[] = new byte[length_of_file]; 
      long total = 0; 
      while ((count = i.read(data))!=1){ 
       total+=count; 
       o.write(data,0,count); 
      } 

      o.flush(); 
      o.close(); 
      i.close(); 

     } catch (MalformedURLException m) { 
      Log.e("Exception", m.toString()); 
     } catch (IOException i) { 
      Log.e("Exception", i.toString()); 
     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(String s) { 
     System.out.println("Downloaded"); 
     super.onPostExecute(s); 
    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
    } 
} 

這個問題似乎是數組數據[]過流或東西嗎? 我不太明白。我已經嘗試使InputStream的緩衝區等於來自length_of_file = getContentLength()的文件大小;

任何幫助將不勝感激! 到目前爲止,相當高興地發現了其他問題(比如讓內部文件夾寫入以及Async Task是什麼......我原來不知道我需要HTTPConnections)。

08-04 15:51:22.938 13454-13486/com.example.johnny.fibre V/Background Response: Length fo target img = 106620 
08-04 15:51:23.058 13454-13486/com.example.johnny.fibre E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2 
                      Process: com.example.johnny.fibre, PID: 13454 
                      java.lang.RuntimeException: An error occurred while executing doInBackground() 
                       at android.os.AsyncTask$3.done(AsyncTask.java:325) 
                       at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354) 
                       at java.util.concurrent.FutureTask.setException(FutureTask.java:223) 
                       at java.util.concurrent.FutureTask.run(FutureTask.java:242) 
                       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
                       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
                       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
                       at java.lang.Thread.run(Thread.java:761) 
                      Caused by: java.lang.ArrayIndexOutOfBoundsException: length=106620; regionStart=0; regionLength=-1 
                       at java.util.Arrays.checkOffsetAndCount(Arrays.java:4857) 
                       at libcore.io.IoBridge.write(IoBridge.java:490) 
                       at java.io.FileOutputStream.write(FileOutputStream.java:316) 
                       at com.example.johnny.fibre.Home$download_image.doInBackground(Home.java:476) 
                       at com.example.johnny.fibre.Home$download_image.doInBackground(Home.java:456) 
                       at android.os.AsyncTask$2.call(AsyncTask.java:305) 
                       at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
                       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)  
                       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)  
                       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)  
                       at java.lang.Thread.run(Thread.java:761)  

回答

0

getContentLength()返回length of the content header,而不是你下載圖像的大小。在這種情況下,您很可能會分配一個不夠大的數組以適合您打算寫入的圖像!

而是分配byte陣列的,爲什麼你讀出的數據不流成ByteArrayOutputStream,並通過調用流getBytes()一旦你完成了獲取結果?

通過這樣做,您根本不需要知道圖像的長度;你只需要繼續閱讀數據,直到你到達InputStream的末尾。

Click here for an example of how to use a ByteArrayOutputStream

作爲一種替代方案,您可能希望利用內建於Android運行時的一些helper utilities,專門用於從URL獲取圖像數據。

+0

謝謝。我會查找ByteArrayOutputStream並返回,如果我有任何問題。 我想緩存圖像以備將來使用,而不是每次需要圖像時都不得不使用活動的Internet套接字...因此Helper Utilities似乎已經停用。 – Jcov

+0

如果使用我引用的幫助程序實用程序,則可以在初始化時或第一次需要時進行聯機調用,然後在本地模型中存儲對映像的引用,以便不必查詢網絡。 –