2013-05-07 94 views
4

我將圖片從網址保存到sdcard。但在SD卡中圖像大小爲0。圖像是在SD卡中創建的,但現在從url中檢索數據並保存。所以它給我的尺寸。將url從網址保存到sdcard

try 
    { 
    URL url = new URL("http://api.androidhive.info/images/sample.jpg"); 
     InputStream input = url.openStream(); 
     try { 
      //The sdcard directory e.g. '/sdcard' can be used directly, or 
      //more safely abstracted with getExternalStorageDirectory() 
      File storagePath = Environment.getExternalStorageDirectory(); 
      OutputStream output = new FileOutputStream (new File(storagePath,username+".png")); 
      try { 
       byte[] buffer = new byte[2048]; 
       int bytesRead = 0; 
       while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) { 
        output.write(buffer, 0, bytesRead); 
       } 
      } finally { 
       output.close(); 
      } 
     } finally { 
      input.close(); 
     } 
    } catch(Exception e) 
    { 
     System.out.println("error in sd card "+e.toString()); 
    } 
+1

你應該有互聯網許可和寫入外部存儲。 – 2013-05-07 08:28:29

回答

5

試試這個code.It工程...

你應該有互聯網的權限和寫入外部存儲。

try 
{ 
    URL url = new URL("Enter the URL to be downloaded"); 
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
    urlConnection.setRequestMethod("GET"); 
    urlConnection.setDoOutput(true);     
    urlConnection.connect();     
    File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile(); 
    String filename="downloadedFile.png"; 
    Log.i("Local filename:",""+filename); 
    File file = new File(SDCardRoot,filename); 
    if(file.createNewFile()) 
    { 
    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.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ; 
    }    
    fileOutput.close(); 
    if(downloadedSize==totalSize) filepath=file.getPath();  
} 
catch (MalformedURLException e) 
{ 
    e.printStackTrace(); 
} 
catch (IOException e) 
{ 
    filepath=null; 
    e.printStackTrace(); 
} 
Log.i("filepath:"," "+filepath) ; 
return filepath; 
+0

我試過並得到totalSize = -1 – user2160008 2013-05-07 08:30:36

+0

我測試模擬器 – user2160008 2013-05-07 08:31:03

+0

檢查設備 – 2013-05-07 10:32:41

2

試試這個,這可能會晚,但它會幫助別人。

private class ImageDownloadAndSave extends AsyncTask<String, Void, Bitmap> 
     { 
      @Override 
      protected Bitmap doInBackground(String... arg0) 
      {   
       downloadImagesToSdCard("",""); 
       return null; 
      } 

       private void downloadImagesToSdCard(String downloadUrl,String imageName) 
       { 
        try 
        { 
         URL url = new URL(img_URL); 
         /* making a directory in sdcard */ 
         String sdCard=Environment.getExternalStorageDirectory().toString();  
         File myDir = new File(sdCard,"test.jpg"); 

         /* if specified not exist create new */ 
         if(!myDir.exists()) 
         { 
          myDir.mkdir(); 
          Log.v("", "inside mkdir"); 
         } 

         /* checks the file and if it already exist delete */ 
         String fname = imageName; 
         File file = new File (myDir, fname); 
         if (file.exists()) 
          file.delete(); 

          /* Open a connection */ 
         URLConnection ucon = url.openConnection(); 
         InputStream inputStream = null; 
         HttpURLConnection httpConn = (HttpURLConnection)ucon; 
         httpConn.setRequestMethod("GET"); 
         httpConn.connect(); 

          if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) 
          { 
          inputStream = httpConn.getInputStream(); 
          } 

          FileOutputStream fos = new FileOutputStream(file); 
       int totalSize = httpConn.getContentLength(); 
         int downloadedSize = 0; 
         byte[] buffer = new byte[1024]; 
         int bufferLength = 0; 
         while ((bufferLength = inputStream.read(buffer)) >0) 
         {     
          fos.write(buffer, 0, bufferLength);     
          downloadedSize += bufferLength;     
          Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ; 
         } 

          fos.close(); 
          Log.d("test", "Image Saved in sdcard..");      
        } 
        catch(IOException io) 
        {     
         io.printStackTrace(); 
        } 
        catch(Exception e) 
        {      
         e.printStackTrace(); 
        } 
       }   
     } 

在AsyncTask中聲明您的網絡操作,因爲它會將其加載爲後臺任務。不要在主線程上加載網絡操作。在這之後無論是在按一下按鈕或內容視圖調用這個類像

new ImageDownloadAndSave().execute(""); 

而且不要忘記添加聯播網,權限爲:

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

希望這將有助於:-)