getCacheDir() 下的子目录

Sub Directories under getCacheDir()

我试图在我的应用程序缓存文件夹中创建子目录,但在尝试检索文件时我什么也没得到。我在下面有一些关于我如何创建子目录以及我如何从中读取的代码,也许我只是做错了什么(很明显我是大声笑)或者这不可能吗? (虽然我没有看到任何你不能看到的地方)。谢谢大家的帮助!

创建子目录

File file = new File(getApplicationContext().getCacheDir(), "SubDir");
                        File file2 = new File(file, each_filename);
                        Toast.makeText(getApplicationContext(), file2.toString(), Toast.LENGTH_SHORT).show();

                        stream = new FileOutputStream(file2);
                        stream.write(bytes);

正在阅读

File file = new File(context.getCacheDir(), "SubDir");
    File newFile = new File(file, filename);

    Note note;

    if (newFile.exists()) {
        FileInputStream fis;
        ObjectInputStream ois;

        try {
            fis = new FileInputStream(new File(file, filename));
            ois = new ObjectInputStream(fis);

            note = (Note) ois.readObject();

            fis.close();
            ois.close();

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }

        return note;
    }

我也试过这个,但什么都没有

String file = context.getCacheDir() + File.separator + "SubDir";

我在您实际创建子目录的地方发布的代码中没有看到任何地方。下面是一些将文件保存在子目录中的示例代码,如果路径尚不存在则调用 mkdirs(此处的某些部分需要包含在适当的 try-catch 中以用于 IOException ,但这应该可以帮助您入门)。

File cachePath = new File(context.getCacheDir(), "SubDir");
String filename = "test.jpeg";
boolean errs = false;

if( !cachePath.exists() ) {
    // mkdir would work here too if your path is 1-deep or
    // you know all the parent directories will always exist
    errs = !cachePath.mkdirs();
}

if(!errs) {
    FileOutputStream fout = new FileOutputStream(cachePath + "/" + filename);
    fout.write(bytes.toByteArray());
    fout.flush();
    fout.close();
}

您需要使用 mkdir 创建您的目录。

在您的代码中:

File file = new File(getApplicationContext().getCacheDir(), "SubDir");
file.mkdir();
File file2 = new File(file, each_filename);