gpt4 book ai didi

java - getCacheDir() 下的子目录

转载 作者:行者123 更新时间:2023-12-02 11:02:30 26 4
gpt4 key购买 nike

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

创建子目录

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();
}

关于java - getCacheDir() 下的子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51217498/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com