A Safe Path to External Storage

前端 未结 5 1636
暗喜
暗喜 2020-12-22 11:14

For my app, I have a fairly large database that needs to be stored on the user\'s device. I plan to change this in the future. For now, however, I\'d like to store it to the

5条回答
  •  甜味超标
    2020-12-22 11:57

    I have a samsung galaxy s3 (running android 4.1.2) and my internal memory is named sdCard0 and My external sd card named as extSdCard.

    So Environment.getExternalStorageDirectory() returned the path of sdCard0 which my internal phone memory

    In such cases you can use the following to get the actual path of the external storage. However this is not recommended. I suggest you follow the docs

    http://developer.android.com/guide/topics/data/data-storage.html

    String externalpath = new String();
    String internalpath = new String();
    
    public  void getExternalMounts() {
    Runtime runtime = Runtime.getRuntime();
    try
    {
    Process proc = runtime.exec("mount");
    InputStream is = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    String line;
    
    BufferedReader br = new BufferedReader(isr);
    while ((line = br.readLine()) != null) {
        if (line.contains("secure")) continue;
        if (line.contains("asec")) continue;
    
        if (line.contains("fat")) {//external card
            String columns[] = line.split(" ");
            if (columns != null && columns.length > 1) {
                externalpath = externalpath.concat("*" + columns[1] + "\n");
            }
    } 
            else if (line.contains("fuse")) {//internal storage
            String columns[] = line.split(" ");
            if (columns != null && columns.length > 1) {
                internalpath = internalpath.concat(columns[1] + "\n");
            }
        }
    }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    System.out.println("Path  of sd card external............"+externalpath);
    System.out.println("Path  of internal memory............"+internalpath);
    }
    

    The above works in most cases

     File dir = new File(externalpath + "/MyFolder");
     if(!dir.exists)
     {
     dir.mkdirs();
     dir.setReadOnly();
     }
    

    Don't forget to add permission in manifest file

      
    

    Also you should check if the sdcard is mounted on your device

      if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)
      {
           // sdcard mounted
      } 
    

提交回复
热议问题