首先阅读有关文件存储选项的官方文档。请记住,外部存储并不等同于“可移动 SD 卡”。它可以很容易地成为 32Gb 或 Nexus 设备上的任何内存。
这是一个如何获取文件目录的基本文件夹的示例(即卸载应用程序时被删除的文件夹,而不是即使在卸载后仍然存在的缓存目录):
String baseFolder;
// check if external storage is available
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
baseFolder = context.getExternalFilesDir(null).getAbsolutePath()
}
// revert to using internal storage
else {
baseFolder = context.getFilesDir().getAbsolutePath();
}
String string = "hello world!";
File file = new File(basefolder + "test.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(string.getBytes());
fos.close();
更新:由于您需要通过 USB 和您的 PC 文件管理器而不是 DDMS 或类似文件访问该文件,您可以使用Environment.getExternalStoragePublicDirectory()并将Environment.DIRECTORY_DOWNLOADS作为参数传递(请注意,我不确定是否有等效的用于内部存储):
String baseFolder;
// check if external storage is available
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
baseFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
}
// revert to using internal storage (not sure if there's an equivalent to the above)
else {
baseFolder = context.getFilesDir().getAbsolutePath();
}
String string = "hello world!";
File file = new File(basefolder + File.separator + "test.txt");
file.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(file);
fos.write(string.getBytes());
fos.flush();
fos.close();