在我的应用程序中,我想在缓存文件夹中创建一个文本文件,首先要做的是在缓存目录中创建一个文件夹。
File myDir = new File(getCacheDir(), "MySecretFolder");
myDir.mkdir();
然后,我想使用以下似乎不在该文件夹中创建的代码在该创建的文件夹中创建一个文本文件。而是,下面的代码在与“缓存”文件夹相同目录的“文件”文件夹中创建文本文件。
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();
}
所以我的问题是,如何正确地指定“ MySecretFolder”来制作文本文件?
我尝试了以下方法:
“ /data/data/com.example.myandroid.cuecards/cache/MySecretFolder”,但是如果我尝试这样做,它会使我的整个应用程序崩溃。我该如何正确地将文本文件保存在cache / MySecretFolder中?
使用getCacheDir()。它将绝对路径返回到文件系统上特定于应用程序的缓存目录。然后您可以创建目录
File myDir = new File(getCacheDir(), "folder");
myDir.mkdir();
请尝试,这可能会对您有所帮助。
好的,如果要在特定文件夹中创建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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句