无法将图像保存到SD卡

时间:2012-02-17 19:22:07

标签: java android

我尝试使用此代码下载图像并保存: 在这一行:

OutputStream os =new FileOutputStream(f);

我在模拟器上尝试它。我的应用程序获得例外,没有权限保存到此路径:

java.io.FileNotFoundException: /mnt/sdcard/InterFlora/1221618532: open failed: EACCES (Permission denied)

我也添加了这一行:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

这是代码:

   RetreiveImage extends AsyncTask<String, Void,Bitmap> {
           Item m_item;
           File f;

           public RetreiveImage(Item aItem , File aFile){
               m_item = aItem;
               f = File (m_Sdcard.getAbsolutePath() + "/myFolder");
           }

        @Override
        protected Bitmap doInBackground(String... params) {

        try
        {
            Bitmap bitmap=null;
            InputStream is=new URL(m_item.small).openStream();
            OutputStream os =new FileOutputStream(f);
            os.close();

            return bitmap;
        }
        catch (MalformedURLException e) {
            return null;
        } catch (IOException e) {
            return null;
        }
    }
}

修改

File m_Sdcard = Environment.getExternalStorageDirectory();
File cacheDir =new File (m_Sdcard.getAbsolutePath() + "/MyFolder");
if(!cacheDir.exists())
cacheDir.mkdirs();

4 个答案:

答案 0 :(得分:4)

将此行添加到manifest.xml工作!!!

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

答案 1 :(得分:1)

尝试这个来获取文件夹(如果它不存在则创建它),然后像在代码中一样使用f File var:

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

阅读getCacheDir()的链接: http://developer.android.com/reference/android/content/Context.html#getCacheDir%28%29

答案 2 :(得分:0)

 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

答案 3 :(得分:0)

检测外部存储位置的方法比Munish Kapoor的答案要好,因为/ sdcard并不总是正确的文件夹路径。

但之后,您确定/ myfolder是否作为文件夹存在。您应该创建一个指向该位置的文件,并在其上调用mkdirs来创建它。

之后,将文件保存在里面。