Ошибка «Файл не найден» в Android?

#android

#Android

Вопрос:

Я пытаюсь загрузить PDF-файл и сохранить на Android в каком-либо месте.Но почему я получаю эту ошибку?Исключение java.io.FileNotFoundException: http://www.pdf995.com/samples/pdf.pdf Я проверяю свой код на эмуляторе. не могли бы вы сказать мне, почему возникает эта ошибка, потому что, когда я нажимаю на этот URL в браузереhttp://www.pdf995.com/samples/pdf.pdf это дает нам PDF.Но здесь это не дает использовать,

код:

 package com.example.downloadfile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;



public class MainActivity extends Activity {
    int totalSize = 0;
     int downloadedSize = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button b = (Button) findViewById(R.id.b1);
        b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                 //showProgress(dwnload_file_path);

                    new Thread(new Runnable() {
                        public void run() {
                             downloadFile();
                        }
                      }).start();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
      void downloadFile(){

            try {
                URL url = new URL("http://www.pdf995.com/samples/pdf.pdf");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                urlConnection.setRequestMethod("GET");
                urlConnection.setDoOutput(true);

                //connect
                urlConnection.connect();

                //set the path where we want to save the file           
                File SDCardRoot = Environment.getExternalStorageDirectory(); 
                //create a new file, to save the <span id="IL_AD12" class="IL_AD">downloaded</span> file 
                File file = new File(SDCardRoot,"aaa.pdf");

                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 <span id="IL_AD9" class="IL_AD">downloading</span>
                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;
                    // update the progressbar //
                    runOnUiThread(new Runnable() {
                        public void run() {
                            float per = ((float)downloadedSize/totalSize) * 100;
                            //cur_val.setText("Downloaded "   downloadedSize   "KB / "   totalSize   "KB ("   (int)per   "%)" );
                        }
                    });
                }
                //close the output stream when complete //
                fileOutput.close();
                runOnUiThread(new Runnable() {
                    public void run() {
                        // pb.dismiss(); // if you want close it..
                    }
                });         

            } catch (final MalformedURLException e) {
               // showError("Error : MalformedURLException "   e);        
                e.printStackTrace();
            } catch (final IOException e) {
                //showError("Error : IOException "   e);          
                e.printStackTrace();
            }
            catch (final Exception e) {
                //showError("Error : Please <span id="IL_AD4" class="IL_AD">check your</span> internet connection "   e);
            }       
        }

}
  

Ответ №1:

Вызова openConnection() достаточно для последующего доступа к входному потоку. Похоже, что второй вызов connect() является причиной проблемы. Просто удалите эту часть из своего кода, и все будет работать нормально:

 URL url = new URL("http://www.pdf995.com/samples/pdf.pdf");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

//set the path where we want to save the file           
File SDCardRoot = Environment.getExternalStorageDirectory(); 
...
  

Кроме того, если вы хотите показать прогресс во время загрузки, я бы предложил вместо этого использовать AsyncTask . Он создан специально для подобных целей.