简体   繁体   English

将文件读取为字节数组的最快方法

[英]Fastest way to read file as a byte array

What is the fastest way to read a file as a byte array (on Android)? 将文件读取为字节数组的最快方法是什么(在Android上)? The file is about 4 MB. 该文件约为4 MB。 It's inside the assets directory, which means that it's probably compressed. 它在assets目录中,这意味着它可能已压缩。

Currently, I'm doing something like this: 目前,我正在执行以下操作:

byte[] buffer = new byte[4 * 1024 * 1024];
context.getAssets().open(FILE_NAME).read(buffer);

On Android, creating the array takes about 40 ms, reading the file about 120 ms. 在Android上,创建数组大约需要40毫秒,读取文件大约需要120毫秒。 I suspect that the 40 ms consist mostly of filling the array with zeroes. 我怀疑40毫秒主要是用零填充数组。 Can I avoid this? 我可以避免吗?

The file is basically a list of about 100,000 items which need to be searched through quickly. 该文件基本上是大约100,000个需要快速搜索的项目的列表。

You could avoid creating the byte array by using the RandomAccessFile class, with its read method. 您可以避免使用RandomAccessFile类及其读取方法来创建字节数组。 The android page isn't too different, but could also be useful. android 页面没有太大区别,但也可能很有用。 I used RAF for a project to store and retrieve data whenever desired from a specific file. 我将RAF用于一个项目,以便在需要时从特定文件中存储和检索数据。 RAF is very useful for these tasks. RAF对于这些任务非常有用。 However, the more you read and write, of course increases the run-time considerably. 但是,您读写的次数越多,当然会大大增加运行时间。 Here is an example of its usage: 这是一个用法示例:

import java.io.RandomAccessFile;
import java.io.FileNotFoundException;

public class RAFTest {

    public static void main(String[] args) {
        RandomAccessFile raf;
        String metadata = "This is a test file.";

        try {

            raf = new RandomAccessFile(args[0], "rw");
            raf.writeUTF(metadata);
            int[] nums = new int[10];
            for(int i = 0; i < b.length; i++) {
                nums[i] = i;
                raf.writeInt(nums[i].getValue());
            }

            raf.seek(0); // force pointer to beginning

            System.out.println(raf.readUTF());
            int[] c = new int[5];
            int byteJump = 4;
            for(int i = 0; i < c.length; i++) {
                raf.seek(raf.getFilePointer() + byteJump);
                c[i] = raf.readInt();
                System.out.println(c[i]);
            }

        } catch(Exception ex) { }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM