2011-09-08 39 views
0

如何從服務器下載音頻文件的url並將其保存到SD卡。如何從服務器下載音頻文件的url

我使用下面的代碼:

public void uploadPithyFromServer(String imageURL, String fileName) { 

    try { 
     URL url = new URL(GlobalConfig.AppUrl + imageURL); 
     File file = new File(fileName); 

     Log.d("ImageManager", "download begining"); 
     Log.d("ImageManager", "download url:" + url); 
     Log.d("ImageManager", "downloaded file name:" + fileName); 
     /* Open a connection to that URL. */ 
     URLConnection con = url.openConnection(); 

     InputStream is = con.getInputStream(); 
     BufferedInputStream bis = new BufferedInputStream(is, 1024 * 50); 
     FileOutputStream fos = new FileOutputStream("/sdcard/" + file); 
     byte[] buffer = new byte[1024 * 50]; 

     int current = 0; 
     while ((current = bis.read(buffer)) != -1) { 
      fos.write(buffer, 0, current); 
     } 

     fos.flush(); 
     fos.close(); 
     bis.close(); 

    } catch (IOException e) { 
     Log.d("ImageManager", "Error: " + e); 
    } 

} 

上面的代碼不下載音頻文件。 如果menifest文件中使用的任何許可PLZ告訴我..(我用互聯網許可) 請幫助

感謝..

+0

你怎麼知道音頻文件沒有被下載? – slayton

回答

2

還必須添加

android.permission.WRITE_EXTERNAL_STORAGE

權限,如果你想寫入數據到SD卡。

也發佈您的logcat輸出,如果您收到任何IOExceptions。

2

你的例子沒有指定請求方法和一些mimetypes和東西。
在這裏您可以找到mimetypes列表http://www.webmaster-toolkit.com/mime-types.shtml
查找與您相關的mimetypes並將其添加到代碼中指定的mimetypes中。

哦,順便說一句,下面是普通的Java代碼。你將不得不將存儲在SD卡上的文件替換掉。不要有一個仿真器或電話的那一刻 來測試部分也可參閱SD存儲權限的文檔在這裏:http://developer.android.com/reference/android/Manifest.permission_group.html#STORAGE

public static void downloadFile(String hostUrl, String filename) 
    { 
    try {  
    File file = new File(filename); 
    URL server = new URL(hostUrl + file.getName()); 


    HttpURLConnection connection = (HttpURLConnection)server.openConnection(); 
    connection.setRequestMethod("GET"); 
    connection.setDoInput(true); 
    connection.setDoOutput(true); 
    connection.setUseCaches(false); 
    connection.addRequestProperty("Accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-shockwave-flash, */*"); 
    connection.addRequestProperty("Accept-Language", "en-us,zh-cn;q=0.5"); 
    connection.addRequestProperty("Accept-Encoding", "gzip, deflate"); 

    connection.connect(); 
    InputStream is = connection.getInputStream(); 
    OutputStream os = new FileOutputStream("c:/temp/" + file.getName()); 

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

    os.close(); 

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

然後調用,

downloadFile("http://localhost/images/bullets/", "bullet_green.gif"); 

編輯: 壞編碼器我。 將輸入InputStream包裝在BufferedInputStream中。無需指定buffersizes等。
默認值是好的。