创建一个字节的ArrayList

| 我想从wave文件中将字节读取到数组中。由于读取的字节数取决于wave文件的大小,因此我正在创建一个最大大小为1000000的字节数组。但这会导致数组末尾的值为空。因此,我想创建一个动态增加的数组,并且发现ArrayList是解决方案。但是AudioInputStream类的read()函数仅将字节读取到字节数组中!如何将值传递到ArrayList中呢?     
已邀请:
        您可以拥有一个字节数组,例如:
List<Byte> arrays = new ArrayList<Byte>();
将其转换回数组
Byte[] soundBytes = arrays.toArray(new Byte[arrays.size()]);
(然后,您将必须编写一个转换器将
Byte[]
转换为
byte[]
)。 编辑:您错误地使用
List<Byte>
,我将向您展示如何仅用
ByteArrayOutputStream
来阅读
AudioInputStream
AudioInputStream ais = ....;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int read;

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

byte[] soundBytes = baos.toByteArray();
PS如果
frameSize
不等于
1
,则抛出
IOException
。因此,使用字节缓冲区读取数据,如下所示:
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();
    
        
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();
    
        这样的事情应该做:
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-处理该问题留给读者练习!     

要回复问题请先登录注册