Java 中有没有更有效的方法来分解字节数组中的数据? 我编写了以下函数来读取具有固定长度数据字段的二进制文件。但性能确实很慢,我需要读取一个二进制文件,其中有30,000条记录,每条记录长度为300字节,每条记录包含240个字段。 有什么建议吗?
public void breakField(byte[] input) {
ByteArrayInputStream bais = new ByteArrayInputStream(input);
byte[] tmp = new byte[2];
bais.read(tmp);
this.id = new String(tmp);
tmp = new byte[4];
bais.read(tmp);
this.name = new String(tmp);
tmp = new byte[8];
bais.read(tmp);
this.phone = new String(tmp);
tmp = new byte[15];
bais.read(tmp);
this.otherInfo = new String(tmp);
.... more fields...
}
最佳答案
将整个文件读入byte[]
数组,如果文件大于 JVM 内存中可用的空间量,那么您将得到 OutOfMemoryError
.
相反,您可以使用 BufferedReader
与 FileReader
结合使用。这将允许您逐段读取文件,而无需将整个文件加载到内存中。
BufferedReader in = new BufferedReader(new FileReader("/path/to/my/file"));
要逐条记录加载数据,只需在调用 BufferedReader.read
时一次读取 300 个字节即可。 。如果您更喜欢处理单个字段,则不必一次读取 300 个字节,只需读取与下一个字段的长度相对应的字节数即可。
关于java - 拆分字节数组以映射 java 类对象中的字段的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8146755/