我想从服务器下载文件。文件在我的Android设备中成功创建,但该文件是空文件。它没有在文件中写任何东西。
我的文件阅读代码如下:
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, to save the downloaded file
File file = new File(SDCardRoot,pos);
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
fileOutput.close();
}
我调试了代码。 while((bufferLength = inputStream.read(buffer))> 0)条件有问题,因为编译器没有进入这个循环。
我的日志cat错误:
ERROR/ActivityThread(8218): Activity com.sec.android.app.myfiles.DetailsActivity has leaked IntentReceiver com.sec.android.app.myfiles.DetailsActivity$4@42760570 that was originally registered here. Are you missing a call to unregisterReceiver()?
android.app.IntentReceiverLeaked: Activity com.sec.android.app.myfiles.DetailsActivity has leaked IntentReceiver com.sec.android.app.myfiles.DetailsActivity$4@42760570 that was originally registered here. Are you missing a call to unregisterReceiver()?
at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:792)
at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:593)
at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1254)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1241)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1235)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:372)
at
com.sec.android.app.myfiles.DetailsActivity.setLocaleReceiver(DetailsActivity.java:185)
at com.sec.android.app.myfiles.DetailsActivity.onCreate(DetailsActivity.java:121)
at android.app.Activity.performCreate(Activity.java:5206)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
at android.app.ActivityThread.access$600(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4898)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
使用Asynctask从服务器下载文件这是使用进度对话框从服务器下载文件的代码,工作正常..请试试..
package .....;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class facebook1 extends Activity {
Button btnShowProgress;
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
private static String file_url = "yoururl";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
btnShowProgress = (Button) findViewById(R.id.submit1);
btnShowProgress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DownloadFileFromURL().execute(file_url);
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait.....");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
protected static final int BUFFER_SIZE = 0;
@SuppressWarnings("deprecation")
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
File downloadloc = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream(downloadloc
+ "/filenam.ext"); //type the name of file with extension.
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String file_url) {
dismissDialog(progress_bar_type);
}}
}
清单文件:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
> </uses-permission>
答案 1 :(得分:0)
你应该改变
File SDCardRoot = Environment.getExternalStorageDirectory();
到
String SDCardRoot = Environment.getExternalStorageDirectory().getPath();
答案 2 :(得分:0)
从API 14开始,主线程不支持网络操作。如果您在主线程中使用AsyncTask并使用14或更高版本的SDK,请尝试使用AsyncTask。