Storing data on SD Card in Android

和自甴很熟 提交于 2019-12-21 04:26:08

问题


Using the data-storage page in the docs, I've tried to store some data to the SD-Card. This is my code:

    // Path to write files to
    String path = Environment.getExternalStorageDirectory().getAbsolutePath() +
                  "/Android/data/"+ctxt.getString(R.string.package_name)+"/files/";
    String fname = "mytest.txt";

    // Current state of the external media
    String extState = Environment.getExternalStorageState();

    // External media can be written onto
    if (extState.equals(Environment.MEDIA_MOUNTED))
    {
        try {
            // Make sure the path exists
            boolean exists = (new File(path)).exists();  
            if (!exists){ new File(path).mkdirs(); }  

            // Open output stream
            FileOutputStream fOut = new FileOutputStream(path + fname);

            fOut.write("Test".getBytes());

            // Close output stream
            fOut.flush();
            fOut.close();

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

When I create the new FileOutputStream I get a FileNotFound exception. I have also noticed that "mkdirs()" does not seem to create the directory.

Can anyone tell me what I'm doing wrong?

I'm testing on an AVD with a 2GB sd card and "hw.sdCard: yes", the File Explorer of DDMS in Eclipse tells me that the only directory on the sdcard is "LOST.DIR".


回答1:


Have you given your application permission to write to the SD Card?

You do this by adding the following to your AndroidManifest.xml:

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



回答2:


Before reading or writing to SD card, don't forget to check the SD card is mounted or not?

Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)


来源:https://stackoverflow.com/questions/2895853/storing-data-on-sd-card-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!