54

我正在从 android 编程音板。问题是有些声音有效,有些无效。这是我对不起作用的声音的回溯

05-31 13:23:04.227 18440 18603 W System.err: java.io.FileNotFoundException: This file can not be opened as a file descriptor; it is probably compressed
05-31 13:23:04.227 18440 18603 W System.err:    at android.content.res.AssetManager.openAssetFd(Native Method)
05-31 13:23:04.227 18440 18603 W System.err:    at android.content.res.AssetManager.openFd(AssetManager.java:331)
05-31 13:23:04.227 18440 18603 W System.err:    at com.phonegap.AudioPlayer.startPlaying(AudioPlayer.java:201)
05-31 13:23:04.227 18440 18603 W System.err:    at com.phonegap.AudioHandler.startPlayingAudio(AudioHandler.java:181)
05-31 13:23:04.235 18440 18603 W System.err:    at com.phonegap.AudioHandler.execute(AudioHandler.java:64)
05-31 13:23:04.235 18440 18603 W System.err:    at com.phonegap.api.PluginManager$1.run(PluginManager.java:86)
05-31 13:23:04.235 18440 18603 W System.err:    at java.lang.Thread.run(Thread.java:1096)

有任何想法吗?

4

13 回答 13

111

您可以为某些扩展禁用资产压缩,如下所示:

android {
    aaptOptions {
        noCompress "pdf"
    }
}

资源

于 2015-10-27T03:50:08.987 回答
49

使用 TensorFlow Lite 文件的人遇到了这个问题,

将以下行添加到块内的Gradle 文件 ( android/app/build.gradle) 中。android{}

aaptOptions {
    noCompress "tflite"
}
于 2019-07-29T07:57:38.000 回答
43

在 assets 文件夹中打开压缩文件是有限制的。这是因为解压后的文件可以直接内存映射到进程的虚拟地址空间,从而避免了再次需要相同数量的内存进行解压。

处理 Android 应用程序中的资产压缩讨论了处理压缩文件的一些技术。aapt您可以通过使用未压缩的扩展名(例如)来欺骗不压缩文件,mp3或者您可以手动将它们添加到未压缩的文件中,apk而不是开始aapt工作。

于 2011-05-31T11:48:55.677 回答
9

您应该禁用该文件的压缩。只需添加:

    aaptOptions {
       noCompress "your-file-name"
    }

到你的app级build.gradle文件里面android { }

于 2018-10-26T11:35:14.850 回答
5

之所以会出现这种令人恼火的情况,是因为在.apk构建时,一些资产在存储之前被压缩,而其他资产则被视为已经压缩(例如图像、视频)并被单独保留。后一组可以使用 打开openAssetFd,前一组不能 - 如果你尝试,你会得到“这个文件不能作为文件描述符打开;它可能是压缩的”错误。

一种选择是欺骗构建系统不压缩资产(请参阅@nicstrong 答案中的链接),但这很繁琐。最好尝试以更可预测的方式解决问题。

我想出的解决方案使用了这样一个事实,即虽然您无法AssetFileDescriptor为资产打开一个,但您仍然可以打开一个InputStream. 您可以使用它来将资产复制到应用程序的文件缓存中,然后为此返回一个描述符:

@Override
public AssetFileDescriptor openAssetFile(final Uri uri, final String mode) throws FileNotFoundException
{
    final String assetPath = uri.getLastPathSegment();  // or whatever

    try
    {
        final boolean canBeReadDirectlyFromAssets = ... // if your asset going to be compressed?
        if (canBeReadDirectlyFromAssets)
        {
            return getContext().getAssets().openFd(assetPath);
        }
        else
        {
            final File cacheFile = new File(getContext().getCacheDir(), assetPath);
            cacheFile.getParentFile().mkdirs();
            copyToCacheFile(assetPath, cacheFile);
            return new AssetFileDescriptor(ParcelFileDescriptor.open(cacheFile, MODE_READ_ONLY), 0, -1);
        }
    }
    catch (FileNotFoundException ex)
    {
        throw ex;
    }
    catch (IOException ex)
    {
        throw new FileNotFoundException(ex.getMessage());
    }
}

private void copyToCacheFile(final String assetPath, final File cacheFile) throws IOException
{
    final InputStream inputStream = getContext().getAssets().open(assetPath, ACCESS_BUFFER);
    try
    {
        final FileOutputStream fileOutputStream = new FileOutputStream(cacheFile, false);
        try
        {
            //using Guava IO lib to copy the streams, but could also do it manually
            ByteStreams.copy(inputStream, fileOutputStream); 
        }
        finally
        {
            fileOutputStream.close();
        }
    }
    finally
    {
        inputStream.close();
    }
}

这确实意味着您的应用程序会留下缓存文件,但这很好。它也不会尝试重用您可能关心或不关心的现有缓存文件。

于 2014-06-19T04:19:34.820 回答
4

这个异常可以通过调用来抛出:

final AssetFileDescriptor afd = activity.getAssets().openFd(path);

我通过将文件保存在res/raw目录而不是资产文件夹中来解决问题,然后以AssetFileDescriptor这种方式获得:

final AssetFileDescriptor afd = activity.getResources().openRawResourceFd(rawId);

然后FileNotFoundException消失了,文件不再压缩。

于 2018-09-05T07:29:18.257 回答
3

只有在尝试打开FileDesriptor. 对于仅读取文件,您可以通过InputStream( AssetManager.open("filename.ext"))。这对我有用。

如果您提前需要文件大小,则需要FileDescriptor(因此是未压缩的文件)调用其getLength()方法,否则您必须读取整个流以确定其大小。

于 2013-07-22T13:22:35.643 回答
2

我已经走了一圈,我使用:

ParcelFileDescriptor mFileDescriptor = context.getAssets().openFd(file).getParcelFileDescriptor();

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

而不是这个实现,我直接使用 ParcelFileDescriptor 中的函数打开文件。

private void openRenderer(Context context,String fileName) throws IOException {  

File file=  FileUtils.fileFromAsset(context, fileName);
        ParcelFileDescriptor parcelFileDescriptor = ParcelFileDescriptor.open(file,ParcelFileDescriptor.MODE_READ_WRITE); 

        mPdfRenderer = new PdfRenderer(parcelFileDescriptor);
    }`

    public class FileUtils {
    private FileUtils() {
    }

    public static File fileFromAsset(Context context, String assetName) throws IOException {
        File outFile = new File(context.getCacheDir(), assetName );
        copy(context.getAssets().open(assetName), outFile);

        return outFile;
    }

    public static void copy(InputStream inputStream, File output) throws IOException {
        FileOutputStream outputStream = null;

        try {
            outputStream = new FileOutputStream(output);
            boolean read = false;
            byte[] bytes = new byte[1024];

            int read1;
            while((read1 = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read1);
            }
        } finally {
            try {
                if(inputStream != null) {
                    inputStream.close();
                }
            } finally {
                if(outputStream != null) {
                    outputStream.close();
                }

            }

        }

    }
}
于 2015-07-15T08:20:16.123 回答
1

刚刚在 build.gradle 中添加了我的文件的扩展名,如下所示并解决了我的问题

android {
   aaptOptions {
      noCompress "tflite"
      noCompress "txt"
      noCompress "pdf"
   }
}
于 2020-11-23T14:38:28.307 回答
0

如果要从 assets 文件夹中获取的文件大于 1MB,那么对我有用的是将文件压缩为 zip 文件,然后在使用前解压缩,并将其存储在未压缩的外部存储中。

InputStream fileInputStream = getAssets().open("your_file.your_file_extension.zip");
unzipInputStream(fileInputStream, "your_folder_in_external_storage");

unzipInputStream我使用的方法是这样的:

public static void unzipInputStream(InputStream inputStream, String location)
{
    try {
        if ( !location.endsWith(File.separator) ) {
            location += File.separator;
        }
        File f = new File(location);
        if(!f.isDirectory()) {
            f.mkdirs();
        }
        ZipInputStream zin = new ZipInputStream(new BufferedInputStream(inputStream, BUFFER_SIZE));
        try {
            ZipEntry ze;
            while ((ze = zin.getNextEntry()) != null) {
                String path = location + ze.getName();
                File unzipFile = new File(path);

                if (ze.isDirectory()) {
                    if(!unzipFile.isDirectory()) {
                        unzipFile.mkdirs();
                    }
                } else {
                    createParentDirectoriesIfMissing(unzipFile);
                    unzipFile(zin, unzipFile);
                }
            }
        } finally {
            zin.close();
        }
    } catch (Exception e) {
        Log.e("", "Unzip exception", e);
    }
}

private static void createParentDirectoriesIfMissing(File unzipFile)
{
    File parentDir = unzipFile.getParentFile();
    if ( null != parentDir ) {
        if ( !parentDir.isDirectory() ) {
            parentDir.mkdirs();
        }
    }
}

private static void unzipFile(ZipInputStream zin, File unzipFile) throws IOException
{
    int size;
    byte[] buffer = new byte[BUFFER_SIZE];
    FileOutputStream out = new FileOutputStream(unzipFile, false);
    BufferedOutputStream fout = new BufferedOutputStream(out, BUFFER_SIZE);

    try {
        while ( (size = zin.read(buffer, 0, BUFFER_SIZE)) != -1 ) {
            fout.write(buffer, 0, size);
        }

        zin.closeEntry();
    } finally {
        fout.flush();
        fout.close();
    }
}
于 2018-11-10T12:32:11.337 回答
0

就我而言,它是由 resource.arsc 引起的,它被压缩了。用未压缩的 resource.arsc 重建解决了这个问题。

于 2020-12-30T04:01:38.823 回答
0

我刚刚遇到了同样的问题,因为gnome-sound-recorder创建了 OGG 文件,我无法使用 MediaPlayer 播放这些文件。所以我用ffmpeg将它们转换为 MP3并且它起作用了。所以我想这是最简单的方法。

ffmpeg -i youroggfile yournewfile.mp3

我还注意到它仍然在资源中显示一个问号,并且当我使用R.raw.yournewfile访问它时,我没有在代码中编写“.mp3”扩展名。

于 2019-11-12T15:45:45.843 回答
0

我遇到了同样的问题,我将文件从 res/raw 复制到 /data/data/your.app.pkg/cache 文件夹,然后一切顺利:D

AssetFileDescriptor afd = null;
try {
    File cache = new File(getCacheDir(), "my_data.dat");
    if (!cache.exists()) {
        copyInputStreamToFile(getResources().openRawResource(R.raw.my_data), cache);
    }
    afd = new AssetFileDescriptor(ParcelFileDescriptor.open(cache, ParcelFileDescriptor.MODE_READ_ONLY), 0, AssetFileDescriptor.UNKNOWN_LENGTH);
} catch (Exception e) {
    e.printStackTrace();
}


private void copyInputStreamToFile(InputStream in, File file) {
    BufferedOutputStream bfos = null;

    try {
        bfos = new BufferedOutputStream(new FileOutputStream(file));
        byte[] buf = new byte[4096];

        int len;
        while ((len = in.read(buf)) != -1) {
            bfos.write(buf, 0, len);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (bfos != null) {
                bfos.close();
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
于 2020-09-02T12:17:08.187 回答