Failed to save image to sdcard

后端 未结 4 1831
别跟我提以往
别跟我提以往 2021-01-13 17:11

I try to download an image with this code and save it : in this line:

OutputStream os =new FileOutputStream(f);

i try it on the emulator.my

相关标签:
4条回答
  • 2021-01-13 17:51
     Try this works..
    
     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.content.Context;
     import android.content.Intent;
      import android.net.Uri;
      import android.os.AsyncTask;
      import android.os.Bundle;
      import android.util.Log;
      import android.view.View;
      import android.view.View.OnClickListener;
      import android.widget.Button;
    
      public class main extends Activity {
      /** Called when the activity is first created. */
        public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
        private Button startBtn;
        private ProgressDialog mProgressDialog;
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            startBtn = (Button)findViewById(R.id.startBtn);
            startBtn.setOnClickListener(new OnClickListener(){
                public void onClick(View v) {
                    startDownload();
                }
            });
        }
    
        private void startDownload() {
            String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
            new DownloadFileAsync().execute(url);
    
        }
        @Override
        protected Dialog onCreateDialog(int id) {
            switch (id) {
            case DIALOG_DOWNLOAD_PROGRESS:
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("Downloading file..");
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(false);
                mProgressDialog.show();
                return mProgressDialog;
            default:
                return null;
            }
        }
    
    class DownloadFileAsync extends AsyncTask<String, String, String> {
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }
    
        @Override
        protected String doInBackground(String... aurl) {
            int count;
    
        try {
    
        URL url = new URL(aurl[0]);
        URLConnection conexion = url.openConnection();
        conexion.connect();
    
        int lenghtOfFile = conexion.getContentLength();
        Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
        FileOutputStream obj;
        InputStream input = new BufferedInputStream(url.openStream());
        //obj=openFileOutput("some_photo_from_gdansk_poland.jpg", Context.MODE_PRIVATE);
        String Path="/sdcard/";//"/data/data/com.server/";
    
        OutputStream output = new FileOutputStream(Path+"some_photo_from_gdansk_poland.jpg");//obj
    
        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) {}
        return null;
    
        }
        protected void onProgressUpdate(String... progress) {
             Log.d("ANDRO_ASYNC",progress[0]);
             mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }
    
        @Override
        protected void onPostExecute(String unused) {
            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        }
    }
    
       }
    
      and add android.permission.WRITE_EXTERNAL_STORAGE
    
    0 讨论(0)
  • 2021-01-13 17:57

    Try this to get the folder (and create it if it doesn't exist) and then use the f File var as you were doing in your code:

        File cacheDirectory;
    
        if ( android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED ))
            cacheDirectory = new File( android.os.Environment.getExternalStorageDirectory(), "myFolder/" );
        else
            cacheDirectory = this.getCacheDir();
    
        if( !cacheDirectory.exists() )
            cacheDirectory.mkdirs();
    
        File f = new File( cacheDirectory, "my_file.jpg" );
    

    Read the link for getCacheDir(): http://developer.android.com/reference/android/content/Context.html#getCacheDir%28%29

    0 讨论(0)
  • 2021-01-13 18:01

    Your way to detect external storage location is better than the answer of Munish Kapoor as /sdcard is not always the right folder path.

    But afterwards, are you sure that /myfolder exists as a folder. You should create a file that points to that location and call mkdirs on it to create it.

    After that, save your file inside.

    0 讨论(0)
  • 2021-01-13 18:04

    Adding this line to the manifest.xml worked!!!

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
    0 讨论(0)
提交回复
热议问题