How to read from the internal storage (subfolder Download)?

懵懂的女人 提交于 2019-12-13 07:36:50

问题


After intensive search I could not find out how to read a configuration file (xml) from the internal storage (sub-folder download). I tried to access /mnt/sdcard/Download/config.xml but received an Exception.

When trying to get the available folders from the two possible suppliers ApplicationContext and Environment, I get these informations:

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

When I try these information to access the config.xml in the Download-folder (I manually copied the file over the Windows explorer) I receive errors, e.g. FileNotFoundException or IllegalArgumentException.

Where is my file, and how can I access it properly?


回答1:


  1. Set the Read-Permission in your AndroidManifest.xml:

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    
  2. Use the following code:

    String filename = Environment.getExternalStorageDirectory().getPath() + File.separator + "download" + File.separator + "config.xml";
    
  3. Use filename for whatever you want to do.



回答2:


You may try following code when you face a condition to read a file from a subfolder in internal storage. Sometimes you may get problems with openFileInput whey you trying to passing context. here is the function.

  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;
    }
}


来源:https://stackoverflow.com/questions/25114901/how-to-read-from-the-internal-storage-subfolder-download

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!