如何在Android应用程序中将文件创建到特定文件夹?

Bel*_*gor 2 android

在我的应用程序中,我想在缓存文件夹中创建一个文本文件,首先要做的是在缓存目录中创建一个文件夹。

File myDir = new File(getCacheDir(), "MySecretFolder");
myDir.mkdir();
Run Code Online (Sandbox Code Playgroud)

然后,我想使用以下似乎不在该文件夹中创建的代码在该文件夹中创建一个文本文件。而是,下面的代码在与“缓存”文件夹相同目录的“文件”文件夹中创建文本文件。

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();
            }
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,如何正确地指定“ MySecretFolder”来制作文本文件?

我尝试了以下方法:

“ /data/data/com.example.myandroid.cuecards/cache/MySecretFolder”,但是如果我尝试这样做,它会使我的整个应用程序崩溃。我该如何正确地将文本文件保存在cache / MySecretFolder中

Raj*_*sar 5

使用getCacheDir()。它返回文件系统上特定于应用程序的缓存目录的绝对路径。然后您可以创建目录

File myDir = new File(getCacheDir(), "folder");
myDir.mkdir();
Run Code Online (Sandbox Code Playgroud)

请尝试这样做可能对您有帮助。

好的,如果要在特定文件夹中创建TextFile,则可以尝试以下代码。

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();
    }
Run Code Online (Sandbox Code Playgroud)