创建一个字节的ArrayList

时间:2011-06-14 08:32:05

标签: java arraylist bytearray

我想将波形文件中的字节读入数组。由于读取的字节数取决于波形文件的大小,因此我创建了一个最大大小为1000000的字节数组。但这会导致数组末尾出现空值。所以,我想创建一个动态增加的数组,我发现ArrayList是解决方案。但是AudioInputStream类的read()函数只将字节读入字节数组!我如何将值传递给ArrayList?

3 个答案:

答案 0 :(得分:23)

ArrayList不是解决方案,ByteArrayOutputStream是解决方案。创建一个ByteArrayOutputStream将字节写入其中,然后调用toByteArray()来获取字节。

您的代码应该是什么样子的示例:

in = new BufferedInputStream(inputStream, 1024*32);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] dataBuffer = new byte[1024 * 16];
int size = 0;
while ((size = in.read(dataBuffer)) != -1) {
    out.write(dataBuffer, 0, size);
}
byte[] bytes = out.toByteArray();

答案 1 :(得分:15)

你可以有一个像:

这样的字节数组
List<Byte> arrays = new ArrayList<Byte>();

将其转换回数组

Byte[] soundBytes = arrays.toArray(new Byte[arrays.size()]);

(然后,您必须编写转换器以将Byte[]转换为byte[])。

编辑:您使用的是List<Byte>错误,我只会告诉您如何使用AudioInputStream阅读ByteArrayOutputStream

AudioInputStream ais = ....;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int read;

while((read = ais.read()) != -1) {
    baos.write(read);
}

byte[] soundBytes = baos.toByteArray();

PS 如果IOException不等于frameSize,则会引发1。因此使用字节缓冲区来读取数据,如下所示:

AudioInputStream ais = ....;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;

while((bytesRead = ais.read(buffer)) != -1) {
    baos.write(buffer, 0, bytesRead);
}

byte[] soundBytes = baos.toByteArray();

答案 2 :(得分:4)

这样的事情应该做:

List<Byte> myBytes = new ArrayList<Byte>();

//assuming your javax.sound.sampled.AudioInputStream is called ais

while(true) {
  Byte b = ais.read();
  if (b != -1) { //read() returns -1 when the end of the stream is reached
    myBytes.add(b);
  } else {
    break;
  }
}

很抱歉,如果代码有点不对劲。我有一段时间没有做过Java。

另外,如果你把它实现为while(true)循环,请小心:)

编辑:这是另一种方法,每次读取更多字节:

int arrayLength = 1024;
List<Byte> myBytes = new ArrayList<Byte>();

while(true) {

  Byte[] aBytes = new Byte[arrayLength];
  int length = ais.read(aBytes); //length is the number of bytes read

  if (length == -1) {  //read() returns -1 when the end of the stream is reached
    break; //or return if you implement this as a method
  } else if (length == arrayLength) {  //Array is full
    myBytes.addAll(aBytes);
  } else {  //Array has been filled up to length

    for (int i = 0; i < length; i++) {
      myBytes.add(aBytes[i]);
    }
  }
}

请注意,两个read()方法都会抛出IOException - 处理此问题仍然是读者的练习!