How to initialize a ByteBuffer if you don't know how many bytes to allocate beforehand?

前端 未结 3 1581
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-01 19:24

Is this:

ByteBuffer buf = ByteBuffer.allocate(1000);

...the only way to initialize a ByteBuffer?

What if I have no ide

相关标签:
3条回答
  • 2021-01-01 20:06

    The idea is that it's only a buffer - not the whole of the data. It's a temporary resting spot for data as you read a chunk, process it (possibly writing it somewhere else). So, allocate yourself a big enough "chunk" and it normally won't be a problem.

    What problem are you anticipating?

    0 讨论(0)
  • 2021-01-01 20:16

    Depends.

    Library

    Converting file formats tends to be a solved problem for most problem domains. For example:

    • Batik can transcode between various image formats (including TIFF).
    • Apache POI can convert between office spreadsheet formats.
    • Flexmark can generate HTML from Markdown.

    The list is long. The first question should be, "What library can accomplish this task?" If performance is a consideration, your time is likely better spent optimising an existing package to meet your needs than writing yet another tool. (As a bonus, other people get to benefit from the centralised work.)


    Known Quantities

    • Reading a file? Allocate file.size() bytes.
    • Copying a string? Allocate string.length() bytes.
    • Copying a TCP packet? Allocate 1500 bytes, for example.

    Unknown Quantities

    When the number of bytes is truly unknown, you can do a few things:

    • Make a guess.
    • Analyze example data sets to buffer; use the average length.

    Example

    Java's StringBuffer, unless otherwise instructed, uses an initial buffer size to hold 16 characters. Once the 16 characters are filled, a new, longer array is allocated, and then the original 16 characters copied. If the StringBuffer had an initial size of 1024 characters, then the reallocation would not happen as early or as often.

    Optimization

    Either way, this is probably a premature optimization. Typically you would allocate a set number of bytes when you want to reduce the number of internal memory reallocations that get executed.

    It is unlikely that this will be the application's bottleneck.

    0 讨论(0)
  • 2021-01-01 20:20

    The types of places that you would use a ByteBuffer are generally the types of places that you would otherwise use a byte array (which also has a fixed size). With synchronous I/O you often use byte arrays, with asynchronous I/O, ByteBuffers are used instead.

    If you need to read an unknown amount of data using a ByteBuffer, consider using a loop with your buffer and append the data to a ByteArrayOutputStream as you read it. When you are finished, call toByteArray() to get the final byte array.

    Any time when you aren't absolutely sure of the size (or maximum size) of a given input, reading in a loop (possibly using a ByteArrayOutputStream, but otherwise just processing the data as a stream, as it is read) is the only way to handle it. Without some sort of loop, any remaining data will of course be lost.

    For example:

    final byte[] buf = new byte[4096];
    int numRead;
    
    // Use try-with-resources to auto-close streams.
    try(
      final FileInputStream fis = new FileInputStream(...);
      final ByteArrayOutputStream baos = new ByteArrayOutputStream()
    ) {
      while ((numRead = fis.read(buf)) > 0) {
        baos.write(buf, 0, numRead);
      }
    
      final byte[] allBytes = baos.toByteArray();
    
      // Do something with the data.
    }
    catch( final Exception e ) {
      // Do something on failure...
    }
    

    If you instead wanted to write Java ints, or other things that aren't raw bytes, you can wrap your ByteArrayOutputStream in a DataOutputStream:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    
    while (thereAreMoreIntsFromSomewhere()) {
        int someInt = getIntFromSomewhere();
        dos.writeInt(someInt);
    }
    
    byte[] allBytes = baos.toByteArray();    
    
    0 讨论(0)
提交回复
热议问题