Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 无法从服务器读取文件_Android - Fatal编程技术网

Android 无法从服务器读取文件

Android 无法从服务器读取文件,android,Android,我想从服务器下载文件。文件已在我的android设备中成功创建,但该文件为空文件。它没有在文件中写入任何内容 我的文件读取代码如下: URL url = new URL(urlString); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection

我想从服务器下载文件。文件已在我的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.readbuffer>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)

使用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>
你应该改变

File SDCardRoot = Environment.getExternalStorageDirectory();


从API 14开始,主线程中不支持网络操作。如果在主线程中使用AsyncTask并使用14或更高版本的SDK,请尝试使用AsyncTask。

您是否在清单文件中指定了对sd卡的写入权限..?是的,我已指定了写入权限您需要使用BufferInputStream:BufferedInputStream bis=new BufferedInputStream;请阅读:先生,我正在使用异步任务,我根据我的要求复制粘贴了您的代码,但仍然没有读取上述代码中的文件。问题在于output.write。它不是在写文件我试图从服务器上获取的文件是GIS文件你可以发布日志吗?我有一个类似于你的问题。。。它是solvedsir问题是编译器没有进入while循环
String SDCardRoot = Environment.getExternalStorageDirectory().getPath();