Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create files to a specific folder in android application?

Tags:

android

In my application, I want to create a text file in the cache folder and first what I do is create a folder in the cache directory.

File myDir = new File(getCacheDir(), "MySecretFolder");
myDir.mkdir();

Then I want to create a text file in that created folder using the following code that doesn't seem to make it there. Instead, the code below creates the text file in the "files" folder that is in the same directory as the "cache" folder.

FileOutputStream fOut = null;
            try {
                fOut = openFileOutput("secret.txt",MODE_PRIVATE);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            String str = "data";
            try {
                fOut.write(str.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fOut.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

SO my question is, how do I properly designate the "MySecretFolder" to make the text file in?

I have tried the following:

"/data/data/com.example.myandroid.cuecards/cache/MySecretFolder", but it crashes my entire app if I try that. How should I properly save the text file in the cache/MySecretFolder?

like image 550
Belphegor Avatar asked Aug 31 '15 05:08

Belphegor


1 Answers

use getCacheDir(). It returns the absolute path to the application-specific cache directory on the filesystem. Then you can create your directory

File myDir = new File(getCacheDir(), "folder");
myDir.mkdir();

Please try this maybe helps you.

Ok, If you want to create the TextFile in Specific Folder then You can try to below code.

try {
        String rootPath = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/MyFolder/";
        File root = new File(rootPath);
        if (!root.exists()) {
            root.mkdirs();
        }
        File f = new File(rootPath + "mttext.txt");
        if (f.exists()) {
            f.delete();
        }
        f.createNewFile();

        FileOutputStream out = new FileOutputStream(f);

        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
like image 193
Rajan Bhavsar Avatar answered Sep 20 '22 09:09

Rajan Bhavsar