【问题标题】:How can I use openRawResourcesFd()?如何使用 openRawResource Fd()?
【发布时间】:2013-11-02 14:54:18
【问题描述】:

我在res/raw 中有文件,我想这样打开:

AssetFileDescriptor afd = getResources().openRawResourcesFd();

这允许,例如,通过afd.getLength() 获得确定的文件大小,InputStream.available() 不承诺,即使它似乎通常可以工作。

但是,当我尝试这个时它失败了:

java.io.FileNotFoundException: 这个文件不能作为文件打开 描述符;它可能被压缩了

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

【问题讨论】:

    标签: android aapt


    【解决方案1】:

    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>   
    

    底部的 cmets 是不言自明的。我为txt 插入了例外。请注意,您也可以一起关闭压缩。

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

    <nocompress extension="nocomp"> 
    

    并重命名您的文件,例如,whatever.txt.nocomp。这样,您可以对除特定文件之外的所有内容进行压缩。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-25
      • 1970-01-01
      • 2011-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多