我可以使用以下代码创建和共享一个 .txt 文件:
File path = new File(Environment.getExternalStorageDirectory(), "Folder");
if (!path.exists()) {
path.mkdirs();
}
File exportFile = new File(path, fileName);
FileWriter writer = new FileWriter(exportFile);
writer.append(body);
writer.flush();
writer.close();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(exportFile));
startActivity(intent);
但是,我希望将此文件保存到应用程序的文件夹中,而不是直接保存在 SD 卡上,因此我更改为下面的代码。它似乎不起作用,因为它没有创建文件,并且我尝试导出到的任何应用程序都看不到该文件。
File path = new File(this.getFilesDir(), "exports");
if(!path.exists()){
path.mkdir();
}
有任何想法吗?我尝试过的每件事都不起作用。该文件应该保存在 Android/data/[package name] 文件夹中是吗?
编辑:好的,我无法正常工作,但实际上发现这不是我想要使用的方法,我想将文件保存在 Android/data 文件夹中,为此我需要使用:
getExternalFilesDir(null)