Android:如何检测资产文件夹中的目录?

Kri*_*ris 4 java android file exists

我正在检索这样的文件

String[] files = assetFiles.list("EngagiaDroid"); 
Run Code Online (Sandbox Code Playgroud)

我们如何知道它是文件还是目录?

我想遍历Assets文件夹中的目录,然后复制其所有内容。

Dan*_*nyA 5

我认为一个更通用的解决方案(如果您有子文件夹等)将是这样的(基于您链接到的解决方案,我也将其添加到了那里):

...

copyFileOrDir("myrootdir");
Run Code Online (Sandbox Code Playgroud)

...

private void copyFileOrDir(String path) {
    AssetManager assetManager = this.getAssets();
    String assets[] = null;
    try {
        assets = assetManager.list(path);
        if (assets.length == 0) {
            copyFile(path);
        } else {
            String fullPath = "/data/data/" + this.getPackageName() + "/" + path;
            File dir = new File(fullPath);
            if (!dir.exists())
                dir.mkdir();
            for (int i = 0; i < assets.length; ++i) {
                copyFileOrDir(path + "/" + assets[i]);
            }
        }
    } catch (IOException ex) {
        Log.e("tag", "I/O Exception", ex);
    }
}

private void copyFile(String filename) {
    AssetManager assetManager = this.getAssets();

    InputStream in = null;
    OutputStream out = null;
    try {
        in = assetManager.open(filename);
        String newFileName = "/data/data/" + this.getPackageName() + "/" + filename;
        out = new FileOutputStream(newFileName);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
    } catch (Exception e) {
        Log.e("tag", e.getMessage());
    }

}
Run Code Online (Sandbox Code Playgroud)


Asa*_*ahi -2

您可以使用http://developer.android.com/reference/java/io/File.html#isDirectory ()检查文件是否代表目录。你是这个意思吗?

  • 感谢您的回复。是的,但是当我尝试时,当文件位于您的资产文件夹中时它不起作用。可能是因为文件包含在包中。 (2认同)