0

我可以使用以下代码创建和共享一个 .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)
4

2 回答 2

0

查看

ContextWrapper contextWrapper = new ContextWrapper(context);
File file = contextWrapper.getDir("media", Context.MODE_PRIVATE);

并确保您的manifest文件是否具有必要的权限

于 2014-07-22T17:37:04.790 回答
0
  1. 检查您的 AndroidManifest.xml 中的权限
  2. 检查目录可用性
  3. 检查外部存储的可用性
  4. 检查文件名。它不能包含空格
  5. 检查能够在该文件夹中写入的权限
于 2014-07-22T17:43:12.353 回答