如果你同意一次读取一个字节,可以在循环内使用
我正在读取一个带有InputStream到字节数组的文件,然后将每个字节更改为int。然后我把整型存储到另一个数组中。有没有办法让它更有效率?具体来说,是否有一种方法可以只使用一个数组而不是两个?对于我的程序来说,分配这两个数组花费的时间太长了。
这就是我现在正在做的(is
是InputStream):
byte[] a = new byte[num];
int[] b = new int[num];
try {
is.read(a, 0, num);
for (int j = 0; j < nPixels; j++) {
b[j] = (int) a[j] & 0xFF; //converting from a byte to an "unsigned" int
}
} catch (IOException e) { }
让我们看看…你不能直接读取整型,因为它会尝试一次读取4个字节。你可以说
int_array[j] = (int)is.read();
您是否查看过DataInputStream甚至FileInputStream?还有许多方法允许您直接从InputStream读取特定的数据类型。
我不知道仅凭你提供的信息,这在你的情况下是否可能。
为什么不使用返回int的无参数方法InputStream.read() ?
File file = new File("/tmp/test");
FileInputStream fis = new FileInputStream(file);
int fileSize = (int) file.length(); // ok for files < Integer.MAX_SIZE bytes
int[] fileBytesAsInts = new int[fileSize];
for(int j = 0; j < fileSize; j++) {
fileBytesAsInts[j] = fis.read();
}