【问题标题】:Is there a way to change bytes to ints while reading from an input stream in Java?有没有办法在从 Java 中的输入流中读取时将字节更改为整数?
【发布时间】:2011-10-28 03:52:09
【问题描述】:

我正在将带有 InputStream 的文件读入字节数组,然后将每个字节更改为 int。然后我将 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) { }

【问题讨论】:

  • 我希望你知道 read(byte[] b, int off, int len) 不能保证读取完整的缓冲区。

标签: java android arrays performance


【解决方案1】:

让我们看看...您不能直接读取 int 值,因为它会尝试一次读取 4 个字节。你可以说

int_array[j] = (int)is.read();

如果您可以一次读取一个字节的流,则在循环内。

【讨论】:

  • 感谢您的解决方案。事实证明,运行时间比我以前的要长,所以我想我必须寻找另一种有效编码的方法。
  • 在抽象基类InputStream中,read(byte[])是根据抽象方法read()定义的。但是,子类可以覆盖 read(byte[]) 以使其比简单地使用一堆读取更有效。使用两个数组不应该占用足够的内存,除非你有巨大的数组......另一个解决方案是尝试按原样使用字节数组。太糟糕了 java 没有联合。
  • 不幸的是,我确实有相当大的数组(用于解码图像文件)。对于安卓平台来说,这是一个更大的问题! D:
【解决方案2】:

您是否查看过DataInputStream 甚至FileInputStream?还有更多方法可以让您直接从 InputStream 中读取特定数据类型。

仅凭您提供的信息,我不知道您的情况是否可行。

【讨论】:

  • 在我的例子中,我将流中的每个字节转换为一个 int,我担心像 DataInputStream 这样的东西会将 4 个字节放入一个 int,这不是我想要的。
【解决方案3】:

为什么不使用返回 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();
}

【讨论】:

    猜你喜欢
    • 2011-12-11
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 2014-03-20
    • 1970-01-01
    相关资源
    最近更新 更多