用Java中的字节数组替换BufferedInputStream

时间:2013-02-07 10:15:36

标签: java arrays bufferedinputstream

以下代码使用BufferedInputStream从文件中读取数据,并在chuncks中处理它。我想修改这段代码,以便代替通过流来自文件的数据,我希望它来自一个字节数组。我已经将文件的数据读入一个字节数组,我想使用这个...循环来处理数组数据,而不是使用文件流中的数据。不知道怎么做:

FileInputStream in = new FileInputStream(inputFile);
BufferedInputStream origin = new BufferedInputStream(in, BUFFER);

int count;

while ((count = origin.read(data, 0, BUFFER)) != -1)
{
  // Do something
}

2 个答案:

答案 0 :(得分:4)

您可以使用ByteArrayInputStream将现有字节数组包装到InputStream中,以便您可以从任何其他InputStream读取字节数组:

byte[] buffer = {1,2,3,4,5};
InputStream is = new ByteArrayInputStream(buffer);

byte[] chunk = new byte[2];
while(is.available() > 0) {
    int count = is.read(chunk);
    if (count == chunk.length) {
        System.out.println(Arrays.toString(chunk));
    } else {
        byte[] rest = new byte[count];
        System.arraycopy(chunk, 0, rest, 0, count);
        System.out.println(Arrays.toString(rest));
    } 
}
Output:
[1, 2]
[3, 4]
[5]

答案 1 :(得分:1)

以下内容将把FileInputStream中的所有数据读入字节数组:

FileInputStream input = new FileInputStream (file);
ByteArrayOutputStream output = new ByteArrayOutputStream ();
byte [] buffer = new byte [65536];
int l;
while ((l = input.read (buffer)) > 0)
    output.write (buffer, 0, l);
input.close ();
output.close ();
byte [] data = output.toByteArray ();
相关问题