【问题标题】:How to read from the internal storage (subfolder Download)?如何从内部存储(子文件夹下载)中读取?
【发布时间】:2014-09-26 16:53:23
【问题描述】:

经过深入搜索,我找不到如何从内部存储(子文件夹下载)中读取配置文件(xml)。我尝试访问/mnt/sdcard/Download/config.xml,但收到异常。

当尝试从两个可能的供应商ApplicationContextEnvironment 获取可用文件夹时,我得到了以下信息:

context.getFilesDir().getAbsolutePath(); // /data/data/com.xxx.yyy/files

context.getDir("Download", 0).getAbsolutePath();
// /data/data/com.xxx.yyy/app_Download

context.getDir("Download", 1).getAbsolutePath();
// /data/data/com.xxx.yyy/app_Download

Environment.getExternalStorageDirectory().getAbsolutePath();
// /storage/emulated/0
context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
// /storage/emulated/0/Android/data/com.xxx.yyy/files/Download

Environment.getDataDirectory().getPath();
// /data

当我尝试使用这些信息访问 下载 文件夹中的 config.xml(我通过 Windows 资源管理器手动复制文件)时,我收到错误消息,例如FileNotFoundException 或 IllegalArgumentException。

我的文件在哪里,如何正确访问它?

【问题讨论】:

    标签: android android-sdcard


    【解决方案1】:
    1. 在您的 AndroidManifest.xml 中设置读取权限:

      <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
      
    2. 使用以下代码:

      String filename = Environment.getExternalStorageDirectory().getPath() + File.separator + "download" + File.separator + "config.xml";
      
    3. 使用filename 做任何你想做的事。

    【讨论】:

      【解决方案2】:

      当您遇到从内部存储的子文件夹中读取文件的情况时,您可以尝试以下代码。有时您可能会遇到 openFileInput 问题,因为您尝试传递上下文。 这是功能。

        public String getDataFromFile(File file){  
           StringBuilder data= new StringBuilder();  
          try {
              BufferedReader br = new BufferedReader(new FileReader(file));
              String singleLine;
              while ((singleLine= br.readLine()) != null) {
                  data.append(singleLine);
                  data.append('\n');
              }
              br.close();
              return data.toString();
          }
          catch (IOException e) {
              return ""+e;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-01
        • 2021-01-21
        • 1970-01-01
        • 2013-06-06
        • 1970-01-01
        • 2022-01-09
        • 2020-09-13
        相关资源
        最近更新 更多