简体   繁体   English

在Android中找不到文件错误?

[英]File not found error in android?

I am trying to download pdf file and save on android at some location .But I am getting this error why ? 我正在尝试下载pdf文件并保存在android的某个位置。但是为什么会出现此错误? java.io.FileNotFoundException: http://www.pdf995.com/samples/pdf.pdf I am checking my code on emulator.can you please tell me why this error coming because when I hit this url on browser http://www.pdf995.com/samples/pdf.pdf it give pdf to us .But here it is not giving to use, java.io.FileNotFoundException: http : //www.pdf995.com/samples/pdf.pdf我正在模拟器上检查我的代码。能否请您告诉我为什么会出现此错误,因为当我在浏览器http://上击中该URL时www.pdf995.com/samples/pdf.pdf它给我们提供了pdf。但是在这里,它不是要使用的,

code: 码:

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);
            }       
        }

}

Calling openConnection() is enough to access the input stream later. 调用openConnection()足以在以后访问输入流。 Looks like the second call to connect() is what's causing the problem. 似乎第二次调用connect()是导致问题的原因。 Just strip that part from your code and it will work fine: 只需从代码中删除该部分,即可正常工作:

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(); 
...

As an aside, if you want to show progress during the download, I'd suggest using an AsyncTask instead. AsyncTask ,如果您想在下载过程中显示进度,建议您改用AsyncTask It's tailor-made for uses like this. 它是针对此类用途量身定制的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM