huawei-developersharmonyos

How to get External and Internal storage directory path


I need to get External and Internal storage directory path to find it's size and I am not able to get the path. In android we have

android.os.Enviroment.getExternalStorageDirectory()

Solution

  • From official documents of HarmonyOS - Internal storage and External storage

    You can create a utils class in your project and use the following functions to get the internal and external storage paths:

    /**
     * Returns the absolute path to the directory of the device's internal storage
     *
     * @param context
     * @return
     */
    public static File getInternalStorage(Context context) {
        return context.getFilesDir(); //Can be called directly too
    }
    
    
    /**
     * Returns the absolute path to the directory of the device's primary shared/external storage
     *
     * @param context
     * @return
     */
    public static File getExternalStorage(Context context) {
        File externalFilesDirPath = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
        String externalStoragePath = "";
        int subPathIndex = externalFilesDirPath.getAbsolutePath().indexOf("/emulated/0/");
        if (subPathIndex > 0) {
            subPathIndex += "/emulated/0/".length();
        }
        if (subPathIndex >= 0 && externalFilesDirPath.getAbsolutePath().contains("/storage/")) {
            externalStoragePath = externalFilesDirPath.getAbsolutePath().substring(0, subPathIndex);
        }
        if (externalStoragePath.length() > 0) {
            externalFilesDirPath = new File(externalStoragePath);
        }
        return externalFilesDirPath;
    }
    

    Once you obtain File object, you can call the following functions to get the storage information -