如何在android上的外部存储上写文件到文件?

Ale*_*lex 2 java android

将一些文本写入Android设备上的文件似乎是一项重大努力.从这里给出的答案开始,我已将以下代码实现到我的单个"Hello-World"活动中:

try {
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(this.openFileOutput("config.txt", Context.MODE_PRIVATE));
    outputStreamWriter.write("lalala");
    outputStreamWriter.close();
} catch (IOException e) {
    Log.e("Exception", "File write failed: " + e.toString());
}
Run Code Online (Sandbox Code Playgroud)

这不会引发异常,但似乎有效.但有没有办法"看到"使用File Manageron android 创建的文件?代码片段似乎写入android文件系统上与应用程序本身相关的"秘密"位置(由using控制this.openFileOutput).

咨询不同的谷歌链接(这个 和这个 和这个)我想出以下代码:

File file = new File(this.getExternalFilesDir("temp"), "testfile.txt");
FileOutputStream fileOutput = openFileOutput(file.getName(), Context.MODE_WORLD_WRITEABLE);
fileOutput.write("lalala");
fileOutput.close();
Run Code Online (Sandbox Code Playgroud)

这会引发错误

Error:(55, 19) error: no suitable method found for write(String) method FileOutputStream.write(int) is not applicable (actual argument String cannot be converted to int by method invocation conversion) method FileOutputStream.write(byte[],int,int) is not applicable (actual and formal argument lists differ in length) method OutputStream.write(int) is not applicable (actual argument String cannot be converted to int by method invocation conversion) method OutputStream.write(byte[],int,int) is not applicable (actual and formal argument lists differ in length) method OutputStream.write(byte[]) is not applicable (actual argument String cannot be converted to byte[] by method invocation conversion)
Run Code Online (Sandbox Code Playgroud)

那么怎么做呢?

作为旁注:这仅用于调试/教育目的,并非旨在成为最终应用程序的一部分!

需要明确的是:我想创建中的文件temp目录,我可以用文件管理器看到(该temp目录是在同一水平My Documents ,Music,DCIM,Download等...)

Com*_*are 6

但有没有办法'看到'在Android上使用文件管理器创建的文件?

我不确定你指的是什么"文件管理器",因为Android没有真正拥有的.但是,您正在写入应用程序的内部存储,而该应用程序是私有的.除了在root设备上和通过一些繁琐的Android SDK工具之外,其他应用程序或普通用户无法查看它.

那么怎么做呢?

File file = new File(this.getExternalFilesDir(null), "testfile.txt");
FileOutputStream fileOutput = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter=new OutputStreamWriter(fileOutput);
outputStreamWriter.write("lalala");
outputStreamWriter.flush();
fileOutput.getFD().sync();
outputStreamWriter.close();
Run Code Online (Sandbox Code Playgroud)

也:

  • 请在后台线程上完成这项工作

  • 在Android 4.3(API级别18)和较旧的设备上,您需要拥有WRITE_EXTERNAL_STORAGE使用外部存储的权限

如果您还希望在设备上或开发中机器文件管理器上快速显示此文件,请在关闭文件后使用此文件:

MediaScannerConnection.scanFile(
  this,
  new String[]{file.getAbsolutePath()},
  null,
  null);
Run Code Online (Sandbox Code Playgroud)

(this某些地方Context,例如ActivityService)