我已經開發了應用程序,其中我需要從url下載文件,我試過下面的代碼,但是當我顯示細節時,我得到了0字節。問題在下載文件
代碼::
package com.playmusic;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
public class playmusic extends Activity {
private static String fileName = "shanesh.mp3";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
URL url = new URL("URl");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
Log.v("log_tag", "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, fileName);
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();
} catch (IOException e) {
Log.d("log_tag", "Error: " + e);
}
Log.v("log_tag", "Check: ");
} }
清單:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
什麼是URL url = new URL( 「URL」); ?????????你指定http url嗎? –
雅我指定http在我的網址 –
然後告訴我你在哪裏得到異常??????? –