简体   繁体   中英

Cannot create folder in SdCard, Android

My code used to work but now I can't even make a directory. (Notice that "1" isn't printed to the logcat.) I have no idea what I broke. I am trying to save an image in a folder I create, here is my code:

    String storedir = "/sdcard";
    String separator = "/";
    String mDateTime = formatter.format(cal.getTime());
    File newdir1 = new File(storedir + "/" + mDateTime);
            if (newdir1.mkdir())
                System.out.println("1");

    File newdir2 = new File(storedir + "/" + mDateTime + "/");
            if (newdir2.mkdir())
                System.out.println("2");

   // Fall into the catch because of ;
                if (fileNameLower.indexOf(".jpeg") > 0)
            fileExt = ".jpeg";
                String rand_fileName = Long.toString(System.currentTimeMillis());// +fileExt;
        String last_fileName = rand_fileName + fileExt;
            File storefile = new File(storedir + "/" + mDateTime + "/" + separator
                + last_fileName);
        String picAddress = storedir + "/" + mDateTime + "/" + separator
                + rand_fileName + ".png";
        System.out.println("135 : [" + storefile.toString() + "]/n");

        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        try {
            Log.w("Process : " , "Starting to download process.");
            bos = new BufferedOutputStream(new FileOutputStream(storefile));
            bis = new BufferedInputStream(in);
            int c;
            while ((c = bis.read()) != -1) {
                bos.write(c);
                bos.flush();
            }
            Log.w("Process : " , "The image is downloaded.");
        } catch (Exception exception) {
            exception.printStackTrace();
            throw new Exception("151 : !");
        } finally 
        {
            bos.close();
            bis.close();
        }



04-29 21:29:20.648: W/The image's type(5733): .jpeg
04-29 21:29:20.648: I/System.out(5733): log : [.jpeg]/n
04-29 21:29:20.652: I/System.out(5733): log : [/sdcard/2012-04-29/1335734960650.jpeg]/n
04-29 21:29:20.652: W/Process :(5733): Starting to download process.
04-29 21:29:20.652: W/System.err(5733): java.io.FileNotFoundException: /sdcard/2012-04-29/1335734960650.jpeg (Permission denied)
04-29 21:29:20.672: W/System.err(5733):     at org.apache.harmony.luni.platform.OSFileSystem.open(Native Method)
04-29 21:29:20.672: W/System.err(5733):     at dalvik.system.BlockGuard$WrappedFileSystem.open(BlockGuard.java:232)
04-29 21:29:20.682: W/System.err(5733):     at java.io.FileOutputStream.<init>(FileOutputStream.java:94)
04-29 21:29:20.682: W/System.err(5733):     at java.io.FileOutputStream.<init>(FileOutputStream.java:66)
04-29 21:29:20.682: W/System.err(5733):     at com.mobil.eposta.Baglanti.saveFile(Baglanti.java:345)
04-29 21:29:20.692: W/System.err(5733):     at com.mobil.eposta.Baglanti.saveAttachMent(Baglanti.java:255)
04-29 21:29:20.692: W/System.err(5733):     at com.mobil.eposta.Baglanti.EkiKaydet(Baglanti.java:235)
04-29 21:29:20.692: W/System.err(5733):     at com.mobil.eposta.Baglanti.Position(Baglanti.java:224)
04-29 21:29:20.692: W/System.err(5733):     at com.mobil.eposta.GoruntuleActivity$1.onClick(GoruntuleActivity.java:75)
04-29 21:29:20.707: W/System.err(5733):     at android.view.View.performClick(View.java:2485)
04-29 21:29:20.707: W/System.err(5733):     at android.view.View$PerformClick.run(View.java:9080)
04-29 21:29:20.712: W/System.err(5733):     at android.os.Handler.handleCallback(Handler.java:587)
04-29 21:29:20.712: W/System.err(5733):     at android.os.Handler.dispatchMessage(Handler.java:92)
04-29 21:29:20.712: W/System.err(5733):     at android.os.Looper.loop(Looper.java:123)
04-29 21:29:20.712: W/System.err(5733):     at android.app.ActivityThread.main(ActivityThread.java:3683)
04-29 21:29:20.712: W/System.err(5733):     at java.lang.reflect.Method.invokeNative(Native Method)
04-29 21:29:20.712: W/System.err(5733):     at java.lang.reflect.Method.invoke(Method.java:507)
04-29 21:29:20.722: W/System.err(5733):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-29 21:29:20.732: W/System.err(5733):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-29 21:29:20.732: W/System.err(5733):     at dalvik.system.NativeStart.main(Native Method)

What should I do for the sdcard's mounted situation?

In this code the result is "NOT GOOD" statement. How can I change this situation?

private static boolean  checkExternalMedia()
{
    boolean mExternalStorageAvailable = false;
    boolean mExternalStorageWriteable = false;
    String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // We can read and write the media
        mExternalStorageAvailable = mExternalStorageWriteable = true;
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // We can only read the media
        mExternalStorageAvailable = true;
        mExternalStorageWriteable = false;
    } else {
        // Something else is wrong. It may be one of many other states,
        //  to know is we can neither read nor write
        Log.i("TAG","State="+state+" Not good");
        mExternalStorageAvailable = mExternalStorageWriteable = false;
    }

    Log.i("TAG","Available="+mExternalStorageAvailable+"Writeable="+mExternalStorageWriteable+" State"+state);
    return (mExternalStorageAvailable && mExternalStorageWriteable);
}

You need

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

in your Manifest file. See other questions on stackoverflow for example Permission to write to the SD card

  • Instead of using "/sdcard" constant string, use Environment.getExternalStorageDirectory().getAbsolutePath()

This will give you the sdcard root path (which may not be just "/sdcard" in some devices

  • It's normally "/mnt/sdcard", not "/sdcard". If you want to experiment with things, the first thing to do is get some facts straight.

  • You initialized a "separator" constant, yet you keep on using "/" to create your paths. This is quoted from the code you pasted with your question:

    File storefile = new File(storedir + "/" + mDateTime + + last_fileName); + last_fileName);

Can you see anything wrong with it?

It is much safer and simpler to use the File class to build your paths.

Try it that way:

if (!checkExternalMedia()) {
    // show error dialog here.
    return;
}

File storedir = Environment.getExternalStorageDirectory();

String mDateTime = formatter.format(cal.getTime());
File savedir = new File (storedir, mDateTime);

if (fileNameLower.indexOf(".jpeg") > 0) {
    fileExt = ".jpeg";
}
String rand_fileName = Long.toString(System.currentTimeMillis());// +fileExt;
String last_fileName = rand_fileName + fileExt;

File storefile = new File(storedir, last_fileName);

// create all directories required for that file
if (!storefile.mkdirs()) {
    Log.e("Process", "can't create directories:" + storefile.getParent());
    // return here too
}

// here be streams

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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