Growing ByteBuffer

前端 未结 11 1119
温柔的废话
温柔的废话 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 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); 
        }
    

提交回复
热议问题