【问题标题】:How do I read and write binary files using the NDK and the AssetManager on Android?如何在 Android 上使用 NDK 和 AssetManager 读写二进制文件?
【发布时间】:2020-06-04 01:55:25
【问题描述】:

我有以下问题:

我得到了一个二进制格式的文件,它存储在我的应用程序的资产目录中。 我想读取这个文件并将其内容写入另一个地方。 读取和写入的逻辑对于“普通”文本文件运行良好,但对于二进制文件,我会得到奇怪和意外的行为。如果我读取文本文件,我的文件内容和缓冲区会很好地存储文本。对于二进制文件,缓冲区大部分是空的并且丢失了很多数据。而且我也无法将缓冲区中的内容写入文件内容数组。 这是读取文件的代码:

AAsset* file = AAssetManager_open(Application::AssetManager,
                filePath.c_str(), AASSET_MODE_BUFFER);
        long fileLength = AAsset_getLength(file);
        unsigned char* fileContent = new unsigned char[fileLength];
        int currentByte = 0;
        //256 kb chunk size
        const int BUFFER_SIZE = 1024*256;
        unsigned char buffer[BUFFER_SIZE];
        while(true){
            int bytesRead = AAsset_read(file, buffer, BUFFER_SIZE);
            if(bytesRead <= 0){
                break;
            }
            for(int i=0; i < bytesRead; i++){
                fileContent[currentByte] = buffer[i];
                currentByte++;
            }
        }

我有什么明显的遗漏吗?还是我需要对二进制数据使用不同的数据类型?任何提示表示赞赏:)

【问题讨论】:

  • 不要将资产用于读/写功能,因为它主要用于静态资源。相反,请使用文件存储位置。 stackoverflow.com/questions/21816049/…这可能对你有帮助。
  • 嗯,这并不能真正回答我的问题。我不想将我的所有资产(模型、纹理、场景……)存储在资产目录之外,因为我希望它们与应用程序一起交付并能够编辑其中一些然后编写它们到另一个位置。
  • 对于在移动应用程序执行期间存储文件,您有多种选择:应用程序本地存储、公共存储、SQLite 数据库。 developer.android.com/training/data-storage - 请注意根本没有提到资产。
  • “而且我也无法将缓冲区中的内容写入文件内容数组。” 这到底是什么意思?

标签: android c++ android-ndk binaryfiles


【解决方案1】:

在堆栈上分配 256kb 势必会超出线程的堆栈限制。 为什么不直接写到fileContent:

while(true){
    int bytesRead = AAsset_read(file, fileContent + currentByte, BUFFER_SIZE);
    if(bytesRead <= 0){
        break;
    }
    currentByte += bytesRead;
}

【讨论】:

  • 只有在这种情况下没有BUFFER_SIZE
  • 这不能回答我的问题。
  • 你的问题只显示了阅读部分,这是唯一看起来不对的地方。请编辑您的问题以显示结果。
【解决方案2】:

如果您打算将所有这些 BLOB 保留在内存中一段时间​​,则无需分块读取:

int bytesRead = AAsset_read(file, fileContent, fileLength);
if (bytesRead <= fileLength) {
    LOGW("expected %d bytes, read only %d bytes", fileLength, bytesRead);
}

更好的是,让Android来处理fileContent的分配:

AAsset* file = AAssetManager_open(Application::AssetManager, filePath.c_str(), AASSET_MODE_BUFFER);
long fileLength = AAsset_getLength(file);
unsigned char* fileContent = static_cast<unsigned char*>(AAsset_getBuffer(file));

如果媒体资产真的很长,并且您立即将其(可能进行一些更改)写入文件,则块可能很有用。

PS:当您不再需要使用new 或AAsset_getBuffer() 分配的内存时,请务必释放它。资产也必须关闭:AAsset_close(file)。

【讨论】:

  • 这不起作用。据我所知,读取限制为 1MB 文件。我的文件是 39 MB。
  • 关于这种方法的限制和限制,请阅读stackoverflow.com/a/2870000/192373。您应该将未压缩的媒体文件存储在您的资产中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-29
  • 1970-01-01
  • 1970-01-01
  • 2012-01-26
  • 2018-07-26
相关资源
最近更新 更多