Im having issue finding a solution to this problem. I have a Bytebuffer of chars(lines of text to be exact) and I need to find a sub-string in that buffer. The easiest solution would be to convert that ByteBuffer to a string and then work with that string however that solution requires me to double(at least) the amount of memory I use in the stack(or heap) of my program and I dont want that, I would rather do something along the lines of each line convert it to string and then work with that. Is there and easy way doing that? thanks.
Asked
Active
Viewed 1,956 times
0
-
1Try creating an [InputStream from the ByteBuffer](https://stackoverflow.com/questions/4332264/wrapping-a-bytebuffer-with-an-inputstream), then using a BufferedReader. – daniu Aug 15 '17 at 07:43
-
Thanks for the comment im trying to experiment with ByteArrayInputStream hopefully that will do the trick. – Omri Shneor Aug 15 '17 at 07:58
-
`ByteArrayInputStream` and `ByteBufferInputStream` are NOT the same thing. (Just saying .....) – Stephen C Aug 15 '17 at 08:07
1 Answers
1
You could read from the ByteBuffer
some bytes in a buffer until finding a breakline character or a character that doesn't make part of the String
to find.
You could use this method :
java.nio.ByteBuffer.get(byte[] dst, int offset, int length)
Then convert the bytes into a String
(new String(bytes, yourEncoding))
and check if it contains the String
to match.
Otherwise read the following bytes and repeat the same processing.

davidxxx
- 125,838
- 23
- 214
- 215
-
Isn't it weird that `ByteBuffer.asCharBuffer()` doesn't allow you to specify the encoding? – Kayaman Aug 15 '17 at 08:04
-
It is true. We could also use the instance method of Charset `charset.decode(byteBuffer)` but it will consume more memory – davidxxx Aug 15 '17 at 08:25
-
Yes, but if `ByteBuffer.asCharBuffer()` allowed to specify an encoding, it could be used efficiently as it doesn't copy the buffer, only creates a view of it. – Kayaman Aug 15 '17 at 08:30
-
I agree with Kayman that is why im having issues working with ByteBuffer only and need to convert is to another class.. – Omri Shneor Aug 15 '17 at 08:34