检查 Android 中的 asset 文件夹中是否存在文件

Foo*_*ife 2 android

如何检查android中的assets文件夹中是否存在文件?

我正在使用 Android Studio,但似乎没有资产文件夹。所以我创建了一个。

我正在使用此代码来加载我的字体:

File pdfFile = null;
try {
    pdfFile = new File(new URI(("file:///android_assets/tahoma.ttf")));
    if (pdfFile.exists())
        Toast.makeText(MainActivity.this,"Exist",Toast.LENGTH_LONG).show();
    else
        Toast.makeText(MainActivity.this,"No Exist",Toast.LENGTH_LONG).show();
} catch (URISyntaxException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

Android Studio 0.5.2 中的项目结构:

root-module
|--.idea
|--app
|----build
|----src
|------main
|--------assets
|----------tahoma.ttf
|--------java
|----------source code here
|--------res
|------AndroidManifest.xml
|----build.gradle
Run Code Online (Sandbox Code Playgroud)

buildl.gradle 文件:

apply plugin: 'android'

android {
    compileSdkVersion 19
    buildToolsVersion '19.1.0'
    sourceSets {
        main {
            assets.srcDirs = ['assets']
        }
    }
    defaultConfig {
        minSdkVersion 11
        targetSdkVersion 17
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile files('libs/android-support-v4.jar')

    }
}
Run Code Online (Sandbox Code Playgroud)

col*_*ore 6

您可以使用 AssetManager Api,例如:

AssetManager am = getAssets();
List<String> mapList = Arrays.asList(am.list(""));
Run Code Online (Sandbox Code Playgroud)

  • `Arrays.asList(getResources().getAssets().list("")).contains("myFile")` 来自 http://stackoverflow.com/a/7337516/1815624 的一行 (2认同)