我如何使用openRawResourcesFd()?

我在res / raw中有要打开的文件,如下所示:

AssetFileDescriptor afd = getResources().openRawResourcesFd();

例如,这允许通过afd.getLength()获取确定的文件大小,即使它看起来通常可以工作,InputStream.available()也无法保证此大小.

但是,当我尝试这样做时失败了:

java.io.FileNotFoundException: This file can not be opened as a file
descriptor; it is probably compressed

这些只是小文本文件.有什么问题?

解决方法:

aapt在构建过程中压缩大多数资源.根据引用aapt来源的this article,例外是:

/* these formats are already compressed, or don't compress well */
static const char* kNoCompressExt[] = {
    ".jpg", ".jpeg", ".png", ".gif",
    ".wav", ".mp2", ".mp3", ".ogg", ".aac",
    ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet",
    ".rtttl", ".imy", ".xmf", ".mp4", ".m4a",
    ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2",
    ".amr", ".awb", ".wma", ".wmv"
};

因此,解决此问题的一种方法是通过使用这些扩展名之一重命名文件来欺骗aapt.

这似乎不太令人满意.相反,如果您想在例外列表中添加扩展名,则可以编辑[sdk] /tools/ant/build.xml.在文件中搜索nocompress:

        <aapt executable="${aapt}"
                command="package"
                versioncode="${version.code}"
                versionname="${version.name}"
                debug="${build.is.packaging.debug}"
                manifest="${out.manifest.abs.file}"
                assets="${asset.absolute.dir}"
                androidjar="${project.target.android.jar}"
                apkfolder="${out.absolute.dir}"
                nocrunch="${build.packaging.nocrunch}"
                resourcefilename="${resource.package.file.name}"
                resourcefilter="${aapt.resource.filter}"
                libraryResFolderPathRefid="project.library.res.folder.path"
                libraryPackagesRefid="project.library.packages"
                libraryRFileRefid="project.library.bin.r.file.path"
                previousBuildType="${build.last.target}"
                buildType="${build.target}"
                ignoreAssets="${aapt.ignore.assets}">
            <res path="${out.res.absolute.dir}" />
            <res path="${resource.absolute.dir}" />
            <nocompress extension="txt"/>
            <!-- <nocompress /> forces no compression on any files in assets or res/raw -->
            <!-- <nocompress extension="xml" /> forces no compression on specific file extensions in assets and res/raw -->
        </aapt>   

底部的注释不言自明.我为txt插入了例外.请注意,您也可以同时关闭压缩功能.

或者,创建一个特殊的扩展名:

<nocompress extension="nocomp"> 

然后重命名您的文件,例如,whatever.txt.nocomp.这样,您可以为除特定文件之外的所有文件保留压缩功能.

上一篇:android – AAPT错误:资源drawable / …未找到


下一篇:使用Rally REST API,如何查询和返回* complete * JSON对象?