利用java comms包 向com口发送字节数组数据并读取返回值,发送一切正常,读取返回值采用com口监听事件进行读取,但是读取返回值的时候有些问题:
1. 先定义数组,然后读取到数组里。代码:
    byte[] readBuffer = new byte[50];
    if(input.available() > 0 ) {
       int numBytes = input.read(readBuffer);
    }
  采用这个方法读取时,只能读取到一部分数据(大部分情况只读取了前10个字节),后半部分数据读不到 readbuffer数组中。
2. 一个字节一个字节读取。代码:
  ArrayList<Integer> rec=new ArrayList<Integer>();
  int r;
  while(r=input.read()!=-1 ) {
       recbuf.add(r);
  }
  采用这个方法读取时,读取速度奇慢,严重超时。哪位大侠解决过类似情况或 有其他的读取方法,请指教一二,先谢了。

解决方案 »

  1.   

    可以用ByteArrayOutputStream将InputStream读取到一个byte数组里面InputStream is = new FileInputStream("c:\\1.text");//或从其他地方获取的输入流
    ByteArrayOutputStream baos= new ByteArrayOutputStream();
    int read =-1;
    while( -1 !=(read =is.read()))
    {
    baos.write(read);
    }
    byte[] array = baos.toByteArray();
    baos.close();
    is.close();
      

  2.   

      int numBytes = input.read(readBuffer);
      while(numBytes != -1 ) {
       ....
       numBytes = input.read(readBuffer);
      }
      

  3.   

    InputStream input = new FileInputStream("c:\\1.text"); byte[] readBuffer = new byte[input.available()];
    int len=input.read(readBuffer);
    int  total=0;   while(total<readBuffer.length) {
      
      total+= len;
      input.read(readBuffer, total, readBuffer.length-total);
      }
      input.close();