Android:从服务器下载文件无法解码流

Android:从服务器下载文件无法解码流,android,download,Android,Download,我正在尝试使用android模拟器从服务器下载图像。似乎下载正常,但我无法获取下载的图像。我收到以下错误: Unable to decode stream: java.io.FileNotFoundException: /storage/sdcard/downloadedfile.jpg: open failed: ENOENT (No such file or directory) 这是我使用的代码: public class DownloadActivity extends Activit

我正在尝试使用android模拟器从服务器下载图像。似乎下载正常,但我无法获取下载的图像。我收到以下错误:

Unable to decode stream: java.io.FileNotFoundException: /storage/sdcard/downloadedfile.jpg: open failed: ENOENT (No such file or directory)
这是我使用的代码:

public class DownloadActivity extends Activity {
// button to show progress dialog
Button btnShowProgress;

// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0; 



 // File url to to download     
        private static String file_url = `"http://10.0.2.2:8080/TestAndroid/DownloadServlet/Desert.jpg";`

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);


    // show progress bar button
    btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
    // Image view to show image after downloading
    my_image = (ImageView) findViewById(R.id.my_image);
    /**
     * Show Progress bar click event
     * */
    btnShowProgress.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // starting new Async Task
            new DownloadFileFromURL().execute(file_url);
        }
    });
}

/**
 * Showing Dialog
 * */
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case progress_bar_type: // we set this to 0
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Downloading file. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setMax(100);
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setCancelable(true);
        pDialog.show();
        return pDialog;
    default:
        return null;
    }
}

/**
 * Background Async Task to download file
 * */
class DownloadFileFromURL extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread
     * Show Progress Bar Dialog
     * */
    @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();
            // this will be useful so that you can show a tipical 0-100% progress bar
            int lenghtOfFile = conection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            // Output stream
          //  OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

            byte data[] = new byte[1024];

            long total = 0;
            long startTotalTime = System.currentTimeMillis();
            long passedTime =0;
            long previosTime=0;

            while ((count = input.read(data)) != -1) {
                total += count;
                long endtTime = System.currentTimeMillis();
                long passed;
                passedTime =endtTime - startTotalTime;
              //  passed=passedTime -previosTime ;
               // previosTime = passed ;

                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress(""+(int)((total*100)/lenghtOfFile));
                Log.i("log_lenghtOfFile",lenghtOfFile+"" );
                Log.i("log_total",total+"" );
                Log.i("log_ourcentage",(int)((total*100)/lenghtOfFile)+"" );
                Log.i("log_passed_time",passedTime +"" );
                calculDebitdescendant( total, lenghtOfFile);
               // Log.i("log_Debit",passedTime +"" );
                // writing data to file
              //  output.write(data, 0, count);
            }
            long endTotalTime = System.currentTimeMillis();
            Log.i("log_Total_passed_time",endTotalTime-startTotalTime +"" );

            // flushing output
          //  output.flush();

            // closing streams
         //   output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error***: ", e.getMessage());
        }

        return null;
    }
    public void calculDebitdescendant(long bytesAvailable,long TotalSize){
        long bytesAvailable1 = bytesAvailable;
        long TotalSize1 = TotalSize;
        Log.i("bytesAvailable",bytesAvailable1  +"fonction");
        Log.i("log_ourcentage",(int)(((TotalSize1-bytesAvailable1 )*100)/TotalSize1 )+"% " );
    }

    /**
     * Updating progress bar
     * */
    protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        pDialog.setProgress(Integer.parseInt(progress[0]));
   }

    /**
     * After completing background task
     * Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after the file was downloaded
        dismissDialog(progress_bar_type);

        // Displaying downloaded image into image view
        // Reading image path from sdcard
        String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
        Log.i("imagePath", imagePath);
        // setting downloaded into image view
        my_image.setImageDrawable(Drawable.createFromPath(imagePath));
    }

}
公共类下载活动扩展活动{
//显示进度对话框的按钮
按钮BTN显示进度;
//进度对话框
私人对话;
图像查看我的图像;
//进度对话框类型(0-用于水平进度条)
公共静态最终整数进度条类型=0;
//要下载的文件url
私有静态字符串文件_url=`”http://10.0.2.2:8080/TestAndroid/DownloadServlet/Desert.jpg";`
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//显示进度条按钮
btnShowProgress=(按钮)findViewById(R.id.btnProgressBar);
//图像视图,用于在下载后显示图像
my_image=(ImageView)findViewById(R.id.my_image);
/**
*显示进度条单击事件
* */
btnShowProgress.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//启动新的异步任务
新建DownloadFileFromURL().execute(文件url);
}
});
}
/**
*显示对话框
* */
@凌驾
受保护的对话框onCreateDialog(int id){
开关(id){
案例进度条类型://我们将其设置为0
pDialog=新建进度对话框(此对话框);
setMessage(“正在下载文件,请稍候…”);
pDialog.setUndeterminate(假);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_水平);
pDialog.setCancelable(真);
pDialog.show();
返回pDialog;
违约:
返回null;
}
}
/**
*要下载文件的后台异步任务
* */
类DownloadFileFromURL扩展异步任务{
/**
*在启动后台线程之前
*显示进度条对话框
* */
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
显示对话框(进度条类型);
}
/**
*在后台线程中下载文件
* */
@凌驾
受保护的字符串doInBackground(字符串…f_url){
整数计数;
试一试{
URL=新URL(f_URL[0]);
URLConnection conconnection=url.openConnection();
conconnect.connect();
//这将非常有用,以便您可以显示典型的0-100%进度条
int lenghtOfFile=conconnect.getContentLength();
//下载该文件
InputStream输入=新的BufferedInputStream(url.openStream(),8192);
//输出流
//OutputStream output=新文件OutputStream(“/sdcard/downloaddedfile.jpg”);
字节数据[]=新字节[1024];
长总计=0;
long startTotalTime=System.currentTimeMillis();
long passedTime=0;
长时间=0;
而((计数=输入。读取(数据))!=-1){
总数+=计数;
long-endtTime=System.currentTimeMillis();
早已过去;
passedTime=endtTime-startTotalTime;
//已通过=已通过时间-前置时间;
//previosTime=已通过;
//发布进度。。。。
//在此之后,将调用onProgressUpdate
出版进度(“+(int)((总计*100)/长度文档));
Log.i(“Log_lenghtOfFile”,lenghtOfFile+”);
Log.i(“Log_total”,total+”);
Log.i(“Log_ourcentage”,int)((总计*100)/长办公室)+”);
Log.i(“Log_passed_time”,passedTime+”);
计算子代(总长度、长度);
//Log.i(“Log_Debit”,passedTime+);
//将数据写入文件
//输出.写入(数据,0,计数);
}
long-endTotalTime=System.currentTimeMillis();
Log.i(“Log_Total_passed_time”,endTotalTime startTotalTime+”);
//冲洗输出
//output.flush();
//合流
//output.close();
input.close();
}捕获(例外e){
Log.e(“错误***:”,e.getMessage());
}
返回null;
}
public void calculdebitsubstant(长字节可用,长总大小){
long bytesAvailable 1=字节数Available;
长TotalSize1=总尺寸;
Log.i(“bytesAvailable”,bytesAvailable1+“fonction”);
Log.i(“Log_ourcentage”,(int)((TotalSize1-bytesAvailable1)*100)/TotalSize1)+“%”;
}
/**
*更新进度条
* */
受保护的void onProgressUpdate(字符串…进度){
//设置进度百分比
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
*完成后台任务后
*关闭进度对话框
* **/
@凌驾
受保护的void onPostExecute(字符串文件\u url){
//下载文件后关闭对话框
解雇对话框(进度条类型);
//在图像视图中显示下载的图像
//从SD卡读取图像路径
字符串imagePath=Environment.getExternalStorageDirectory().toString()+“/downloadedfile.jpg”;
Log.i(“imagePath”,imagePath);
//设置已下载到图像视图中
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}

PS:仿真器的SD卡不包含该图像,我将所有权限都放进去了。
如果有人知道错误的来源,请告诉我。谢谢。

我编辑了代码,我可以从服务器下载一张图片到模拟器的SD卡。我刚刚启用了写入功能(我将它们放在注释中)

公共类下载活动扩展活动{
//显示进度的按钮
public class DownloadActivity extends Activity {
// button to show progress dialog
Button btnShowProgress;

// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0; 

// File url to to download     
   // private static String file_url = "http://192.168.1.106:8080/TestAndroid/DownloadServlet/Desert.jpg";
    private static String file_url = "http://10.0.2.2:8080/TestAndroid/DownloadServlet/Desert.jpg";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);


    // show progress bar button
    btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
    // Image view to show image after downloading
    my_image = (ImageView) findViewById(R.id.my_image);
    /**
     * Show Progress bar click event
     * */
    btnShowProgress.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // starting new Async Task
            new DownloadFileFromURL().execute(file_url);
        }
    });
}

/**
 * Showing Dialog
 * */
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case progress_bar_type: // we set this to 0
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Downloading file. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setMax(100);
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setCancelable(true);
        pDialog.show();
        return pDialog;
    default:
        return null;
    }
}

/**
 * Background Async Task to download file
 * */
class DownloadFileFromURL extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread
     * Show Progress Bar Dialog
     * */
    @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();
            // this will be useful so that you can show a tipical 0-100% progress bar
            int lenghtOfFile = conection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            // Output stream
            OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

            byte data[] = new byte[1024];

            long total = 0;
            long startTotalTime = System.currentTimeMillis();
            long passedTime =0;
            long previosTime=0;

            while ((count = input.read(data)) != -1) {
                total += count;
                long endtTime = System.currentTimeMillis();
                long passed;
                passedTime =endtTime - startTotalTime;
              //  passed=passedTime -previosTime ;
               // previosTime = passed ;

                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress(""+(int)((total*100)/lenghtOfFile));
                Log.i("log_lenghtOfFile",lenghtOfFile+"" );
                Log.i("log_total",total+"" );
                Log.i("log_ourcentage",(int)((total*100)/lenghtOfFile)+"" );
                Log.i("log_passed_time",passedTime +"" );
                calculDebitdescendant( total, lenghtOfFile);
               // Log.i("log_Debit",passedTime +"" );
                // writing data to file
                output.write(data, 0, count);
            }
            long endTotalTime = System.currentTimeMillis();
            Log.i("log_Total_passed_time",endTotalTime-startTotalTime +"" );

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error***: ", e.getMessage());
        }

        return null;
    }
    public void calculDebitdescendant(long bytesAvailable,long TotalSize){
        long bytesAvailable1 = bytesAvailable;
        long TotalSize1 = TotalSize;
        Log.i("bytesAvailable",bytesAvailable1  +"fonction");
        Log.i("log_ourcentage",(int)(((TotalSize1-bytesAvailable1 )*100)/TotalSize1 )+"% " );
    }

    /**
     * Updating progress bar
     * */
    protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        pDialog.setProgress(Integer.parseInt(progress[0]));
   }

    /**
     * After completing background task
     * Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after the file was downloaded
        dismissDialog(progress_bar_type);

        // Displaying downloaded image into image view
        // Reading image path from sdcard
        String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
        Log.i("imagePath", imagePath);
        Log.i("isExternalStorageWritable", isExternalStorageWritable() + "true" );
        // setting downloaded into image view
        my_image.setImageDrawable(Drawable.createFromPath(imagePath));
    }

}
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        Log.i("isExternalStorageWritable", "true" );
        return true;
    }
    return false;
}