【问题标题】:Storing a file on Internal And External SdCard在内部和外部 SD 卡上存储文件
【发布时间】:2014-05-05 07:07:27
【问题描述】:

我正在尝试将文件保存在内部和外部 sd 卡上.. 基本上我想给用户一个选项来将文件保存在内部或外部卡上 这就是我在内部 SD 卡中创建文件的方式

File file = new File(Environment.getExternalStorageDirectory()
            + "/Tnt_input/register.html");

但是如何在External SD card...中创建这个文件?

我可以在 DDMS 中看到两个存储

1) sdCard0

2) extSdCard

通过使用上面的代码在sdCard0创建这个文件

【问题讨论】:

    标签: android android-sdcard


    【解决方案1】:

    您可以使用context.getFilesDir() 将文件保存在内部存储中

    File file = new File(context.getFilesDir(), filename);
    String filename = "myfile";
    String string = "Hello world!";
    FileOutputStream outputStream;
    
    try {
      outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
      outputStream.write(string.getBytes());
      outputStream.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    

    查看saving a file to internal storage了解更多信息。

    注意:应用的内部存储目录由应用的包名指定,位于 Android 文件系统的特殊位置。从技术上讲,如果您将文件模式设置为可读,另一个应用程序可以读取您的内部文件。

    Good Example for Save and read file from/to Internal/External storage

    how to differentiate between internal and external SD card path in android?

    【讨论】:

    • 这会在手机内存中创建文件,该文件只能由应用程序评估。我想在可移动存储卡中创建文件..我的手机有 8gb 内部存储,用户可以从中访问 5.8gb,并且提到的代码在这个内部存储中创建文件..
    • @AdilWaqar check this question
    • 意味着我无法区分 android 中的 Internal SdCard 和 External SdCard,因为我的应用程序的目标是 4.0,而 min sdk 版本是 2.3...
    • @AdilWaqar 我发现this 可能会有所帮助
    • 它有帮助 :) 至少现在我可以使用 Environment.isExternalStorageRemovable(); 检查是否安装了外部 sd 卡;但要获得存储文件的路径,我必须做更多的工作......
    【解决方案2】:

    在 Android 4.4 之前,没有找到所有外部 SD 卡内存的标准方法,Environment.getExternalStorageDirectory() 只返回一个这样的内存。为了获得其他记忆,程序员正在解析一些 linux 配置文件。

    从 4.4 (API 19) 开始有:Context.getExternalFilesDir 其中:

    返回所有应用程序特定目录的绝对路径 应用程序可以放置持久化的外部存储设备 它拥有的文件。这些文件是应用程序内部的,而不是 通常作为媒体对用户可见。

    在 4.4 之前,您应该使用 Environment.getExternalStorageDirectory,在 4.4 之后使用 Context.getExternalFilesDir。

    有一篇很好的博客文章详细解释了所有这些:

    http://commonsware.com/blog/2014/04/08/storage-situation-external-storage.html

    【讨论】:

      【解决方案3】:

      终于找到了一个可行的解决方案,但不推荐使用它来获取外部 sd 卡,我使用硬编码路径,例如 /storage/extSdCard/StorageTest/input,但此路径取决于设备,上述路径适用于三星 Galaxy Note 系列,但适用于 xperia Z它的/storage/removable/sdcard1。这个解决方案对我有用,因为我的客户使用特定的设备。但是像这样你不能创建一个适用于每个设备的全局方法,所以这里是对我有用的代码

      String galaxy_note = "/storage/extSdCard";
      File file = new File(galaxy_note
          +"/StorageTest/input");
      

      您也可以通过使用检查设备中是否安装了可移动的sd卡

      Environment.isExternalStorageRemovable();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-20
        • 2015-08-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多