Android: How to detect a directory in the assets folder?

前端 未结 9 1323
无人及你
无人及你 2021-01-05 18:15

I\'m retrieving files like this

String[] files = assetFiles.list(\"EngagiaDroid\"); 

How can we know whether it is a file or is a director

9条回答
  •  自闭症患者
    2021-01-05 18:37

    Another way relying on exceptions:

    private void checkAssets(String path, AssetManager assetManager) {
        String TAG = "CheckAssets";
        String[] fileList;
        String text = "";
        if (assetManager != null) {
            try {
                fileList = assetManager.list(path);
            } catch (IOException e) {
                Log.e(TAG, "Invalid directory path " + path);
                return;
            }
        } else {
            fileList = new File(path).list();
        }
    
        if (fileList != null && fileList.length > 0) {
            for (String pathInFolder : fileList) {
                File absolutePath = new File(path, pathInFolder);
    
                boolean isDirectory = true;
                try {
                    if (assetManager.open(absolutePath.getPath()) != null) {
                        isDirectory = false;
                    }
                } catch (IOException ioe) {
                    isDirectory = true;
                }
    
                text = absolutePath.getAbsolutePath() + (isDirectory ? " is Dir" : " is File");
                Log.d(TAG, text);
                if (isDirectory) {
                    checkAssets(absolutePath.getPath(), assetManager);
                }
            }
        } else {
            Log.e(TAG, "Invalid directory path " + path);
        }
    }
    

    and then just call checkAssets("someFolder", getAssets()); or checkAssets("", getAssets()); if you want to check the root assets folder. But be aware that the root assets folder contains also other directories/files (Eg. webkit, images, etc.)

提交回复
热议问题