简体   繁体   English

从DataInputStream读取int []

[英]Read an int[] from a DataInputStream

I'm looking for a way to read a large number of ints from a DataInputStream and load them into an array. 我正在寻找一种从DataInputStream读取大量int并将其加载到数组中的方法。 I know exactly how many int s I need to read, but it'd be nice if there was a cleaner way than to simply iterate. 我确切地知道我需要读取多少个int ,但是如果有一种比简单地迭代更简洁的方法,那将是很好的。

There is already a way to do this with a byte array, just by using the DataInputStream#read(byte[]) method, but there is no equivalent for int[] . 仅通过使用DataInputStream#read(byte[])方法,就已经存在使用字节数组执行此操作的方法,但是int[]没有等效的方法。 I could obviously read the data into a byte array by creating a byte array with the length multiplied by four, but I really need the data in int s. 通过创建长度乘以四的字节数组,显然可以将数据读取到字节数组中,但是我确实需要int s中的数据。

The way I see it, there are three possibilities I could use: 从我的角度来看,我可以使用三种可能性:

  1. Somehow load the data directly into an int[] . 以某种方式将数据直接加载到int[]
  2. Somehow convert a byte[] into an int[] . 以某种方式将byte[]转换为int[]
  3. Iterate through the array and just use readInt() . 遍历数组,仅使用readInt()

While the first two solutions are much preferred, I currently don't know of a way to do either. 尽管前两种解决方案是首选,但我目前不知道两种解决方案。 Is there any simple way to do this without iteration? 有没有简单的方法可以做到这一点而无需迭代?

It would appear that the only way to do this is a simple for loop and using readInt() . 看来,做到这一点的唯一方法是简单的for循环和使用readInt() This is what I eventually opted to do. 这就是我最终选择要做的。

You could try using a ByteBuffer , which is able to leave the data in the OS memory and therefore reads pretty quick. 您可以尝试使用ByteBuffer ,它能够将数据保留在OS内存中,因此读取速度非常快。 It also has a getInt() method, which should allow you to directly read Integers and put them into your array. 它还有一个getInt()方法,该方法应允许您直接读取Integers并将它们放入数组中。

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

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