简体   繁体   中英

Android app: How do I create a directory in the internal storage

I can't seem to be able to figure out how to create a directory/file through an android app to the internal storage. I have the following code:

public class Environment extends SurfaceView implements SurfaceHolder.Callback {
    public static String FILE_PATH;
    //other unimportant variables

    public Environment(Conext context) {
        super(context);
        FILE_PATH = context.getFilesDir() + "/My Dir/";
        File customDir = new File(FILE_PATH);
        if(!customDir.exists())
            System.out.println("created my dir: " + customDir.mkdir());

        File test = new File(FILE_PATH + "testFile.txt");
        try {
            if(!test.exists())
                System.out.println("created test: " + test.createNewFile());
        } catch(Exception e) {
            e.printStackTrace();
        }
        //other unimportant stuff
    }
}

I then use ES File Explorer to see if it created the file and I don't see the directory/file anywhere despite it printing out "true" for the System.out.println() calls.

What am I doing wrong?

The path where you are creating file is in apps private location. Generally you can't access it from outside. It's actually created in apps data folder. However it seems you want to write in external folder. To write in the external storage, you must request the WRITE_EXTERNAL_STORAGE permission in your manifest file:

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

code:

    String folder_main = "My Dir";

    File f = new File(Environment.getExternalStorageDirectory(), folder_main);
    if (!f.exists()) {
        f.mkdirs();
    }
    File test = new File(f , "testFile.txt");

Here you will find how to you will create folder/file in external storage.

Save a File on External Storage

You can try with below:

ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(getFilesDir().getName(), Context.MODE_PRIVATE);
File file =  new File(directory,”fileName”);
String data = “TEST DATA”;
FileOutputStream fos = new FileOutputStream(“fileName”, true); // save
fos.write(data.getBytes());
fos.close();

This will write file in Device's internal storage (/data/user/0/com.yourapp/)

Hope this helps!

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