简体   繁体   English

如何在Android中将文件正确拆分为字节数组

[英]How to properly split a file into byte arrays in Android

I have a file that I intend to send over the network, so I tried to split it into byte arrays: 我有一个打算通过网络发送的文件,因此我尝试将其拆分为字节数组:

      File myFile = new File(selectedImagePath);
      byte[] fileByteArray = new byte[(int) myFile.length()];
      Log.i("MyApp", " File byte size: " + fileByteArray.length);
      List<byte[]> listOfBytes = new ArrayList<byte[]>();
      int pos = 0;
      while (pos < fileByteArray.length)
      {

        int length = pos + size > fileByteArray.length ? fileByteArray.length - pos : size;
        byte[] act_byte = new byte[length];
        Log.i("MyApp","Length: "+length);
        System.arraycopy(fileByteArray, pos, act_byte, 0, length);
        pos += length;
        listOfBytes.add(act_byte);
      }
      List<byte[]> sending=new ArrayList<byte[]>();
      for(byte[] ba:listOfBytes)
       { 
          byte[] arr = new byte[ba.length + 2]; 
          arr[0] = new Integer(W).byteValue();
          arr[1] = new Integer(Z).byteValue();
          System.arraycopy(ba, 0, arr, 2, ba.length);
          sending.add(arr);
      }

Let the file size be 10000 bytes. 设文件大小为10000字节。

On the receiving size, I get 10000 bytes, yet the file isn't readable. 在接收大小上,我得到10000个字节,但该文件不可读。

    byte[] message = new byte[size + 2];

    DatagramPacket p = new DatagramPacket(message, message.length);
    s = new DatagramSocket(SERVERPORT);
    List<byte[]> incomingBA=new ArrayList<byte[]>();

    while (true)
    {
      s.receive(p);
      int a=new Byte(p.getData()[0]).intValue();
      int b=new Byte(p.getData()[1]).intValue();
      int actualSize = p.getLength();
      byte[] actualBA=new byte[actualSize-2];
      System.arraycopy(p.getData(),2,actualBA,0,actualBA.length);
      incomingBA.add(actualBA);
      if(X==22)
      {            
        byte[] result=concatenateByteArrays(incomingBA);           
        FileOutputStream fos = new FileOutputStream("/mnt/sdcard/Download/X.jpg");
        //BufferedOutputStream bos = new BufferedOutputStream(fos);
        fos.write(result,0,result.length);
        fos.flush();
        fos.close();
        incomingBA.clear();
      }

     public byte[] concatenateByteArrays(List<byte[]> blocks) {
       ByteArrayOutputStream os = new ByteArrayOutputStream();
       for (byte[] b : blocks) {
             os.write(b, 0, b.length);
           }
         return os.toByteArray();
        }

What did I do wrong? 我做错了什么?

I forgot to read the content of the file into the byte array, so I needed to use this code: 我忘了将文件内容读入字节数组,因此需要使用以下代码:

FileInputStream fileInputStream = new FileInputStream(myFile);
fileInputStream.read(fileByteArray);
fileInputStream.close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM