Growing ByteBuffer

前端 未结 11 1116
温柔的废话
温柔的废话 2021-01-31 14:21

Has anyone has ever seen an implementation of java.nio.ByteBuffer that will grow dynamically if a putX() call overruns the capacity?

The reason I want to do it this way

相关标签:
11条回答
  • 2021-01-31 14:55

    A Vector allows for continuous growth

    Vector<Byte> bFOO = new Vector<Byte>(); bFOO.add((byte) 0x00);`

    0 讨论(0)
  • 2021-01-31 14:58

    It may be also worth to have a look at Netty's DynamicChannelBuffer. Things that I find handy are:

    • slice(int index, int length)
    • unsigned operations
    • separated writer and reader indexes
    0 讨论(0)
  • 2021-01-31 15:01

    In order for asynchronous I/O to work, you must have continuous memory. In C you can attempt to re-alloc an array, but in Java you must allocate new memory. You could write to a ByteArrayOutputStream, and then convert it to a ByteBuffer at the time you are ready to send it. The downside is you are copying memory, and one of the keys to efficient IO is reducing the number of times memory is copied.

    0 讨论(0)
  • 2021-01-31 15:01

    I'd suggest using an input stream to receive data from a file (with a sperate thread if you need non-blocking) then read bytes into a ByteArrayOutstream which gives you the ability to get it as a byte array. Heres a simple example without adding too many workarounds.

        try (InputStream inputStream = Files.newInputStream(
                Paths.get("filepath"), StandardOpenOption.READ)){
    
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int byteRead = 0;
    
            while(byteRead != -1){
                byteRead = inputStream.read();
                baos.write(byteRead);
            }
            ByteBuffer byteBuffer = ByteBuffer.allocate(baos.size())
            byteBuffer.put(baos.toByteArray());
    
            //. . . . use the buffer however you want
    
        }catch(InvalidPathException pathException){
            System.out.println("Path exception: " + pathException);
        }
        catch (IOException exception){
            System.out.println("I/O exception: " + exception); 
        }
    
    0 讨论(0)
  • 2021-01-31 15:01

    Netty ByteBuf is pretty good on that.

    0 讨论(0)
  • 2021-01-31 15:01

    To serialize somethiing you will need object in entry. What you can do is put your object in collection of objects, and after that make loop to get iterator and put them in byte array. Then, call ByteBuffer.allocate(byte[].length). That is what I did and it worked for me.

    0 讨论(0)
提交回复
热议问题