【问题标题】:Sub Directories under getCacheDir()getCacheDir() 下的子目录
【发布时间】:2018-12-15 11:34:08
【问题描述】:

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

创建子目录

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";

【问题讨论】:

    标签: java android directory subdirectory


    【解决方案1】:

    我在您发布的代码中没有看到您实际创建子目录的任何地方。这是一些将文件保存在子目录中的示例代码,如果路径尚不存在,则调用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();
    }
    

    【讨论】:

    • 哇,愚蠢的我 xD 我想我只是想写入目录会自动创建它。哇哈哈非常感谢你
    【解决方案2】:

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

    在您的代码中:

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

    【讨论】:

      猜你喜欢
      • 2011-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-11
      • 1970-01-01
      相关资源
      最近更新 更多