1

我想编写一种将文件中的一部分读入字节数组的方法。为此,我正在使用文件输入流和缓冲输入流。

像这样:

fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);

我只通过调用方法名称“OpenFile(String File)”来执行此操作。使用此方法打开文件后,我尝试使用以下功能进行操作:“ReadParts(byte[] buffer, int offset, int len)”

dis.read(buffer, offset, len);            
for(int i = 0; i < buffer.length; i++) System.out.print((char)buffer[i]);

// used data:
// file = "C:\Temp\test.txt" with a size of 949
// buffer: always in this case with a size of 237, except for the last one its 238
// offsets: 0, 237, 474, 711 
// len is always 237, except for the last one its 238

第一步后 dis.read() 行总是抛出 indexOutOfBounds 错误消息,但我不知道为什么和什么。使用 netbeans 调试器没有帮助,因为我找不到索引的问题.....

4

4 回答 4

2

如果您将 Stream 读入缓冲区数组,则您的偏移量和 len 必须始终为:

offset = 0;
len = buffer.length();

这些参数指定将数据放入缓冲区的位置,而不是从 Stream 中读取哪些数据。流是连续读取的(或者无论如何拼写?)!

如果你总是打电话:

buffer = new byte[256];
dis.read(buffer, 0, 256);

这将发生:在第一次调用之前 Streamposition(返回的下一个字节的位置)为 0。

  1. call=256 后的流位置和缓冲区包含字节 0-255
  2. call=512 后的流位置和缓冲区包含字节 256-511
  3. ...

    dis.reset();

流位置再次为 0。

此代码仅将字节 256-511 从 Stream 读取到缓冲区中:

byte[] buffer = new byte[512];
dis.skip(256);
dis.read(buffer, 0, 256);

看到缓冲区的最后 256 个字节没有被填满。这是 read(byte[], int, int) 和 read(byte[]) 之间的区别之一!

这里有一些链接,它们描述了流的概念和读取方法的用法: read() Streams

于 2012-03-14T11:55:01.720 回答
1

你怎么想出offset和len。我现在的猜测是你 offset + len 大于缓冲区。

于 2012-03-14T11:27:30.177 回答
1

你会得到 IndexOutOfBoundsException - 如果

  • 偏移量为负,

  • len 为负数,

  • len 大于 buffer.length - 关闭

第 3 点的示例:

如果输入文件有500个字符或者1500个字符,下面的程序就会运行成功,

byte[] buffer = new byte[1000];
int offset = 0;
int len = 1000;
dis.read(buffer, offset, len);            
for(int i = 0; i < buffer.length; i++) System.out.print((char)buffer[i]);

但它会失败并抛出异常,如果,

byte[] buffer = new byte[1000];
int offset = 0;
int len = 1001;
dis.read(buffer, offset, len); 
for(int i = 0; i < buffer.length; i++) System.out.print((char)buffer[i]);

检查两种情况下的长度值。

于 2012-03-14T11:47:03.253 回答
0

偏移量是缓冲区而不是文件中的偏移量。

我怀疑你想要的是

byte[] buffer = new byte[237];

int len = dis.read(buffer); // read another 237 bytes.

if (len < 0) throw new EOFException(); // no more data.
for(int i = 0; i < len; i++)
   System.out.print((char)buffer[i]);
// or
System.out.print(new String(buffer, 0, 0, len));

在您的调试器中,您可以检查偏移量 >= 0 和偏移量 + 长度 <= buffer.length 吗?

从 InputStream.read()

public int read(byte b[], int off, int len) throws IOException {
if (b == null) {
    throw new NullPointerException();
} else if (off < 0 || len < 0 || len > b.length - off) {
    throw new IndexOutOfBoundsException();

检查的条件之一无效。

于 2012-03-14T11:27:44.597 回答