java bytebuffer slice not working as per documentation -
i have been working bytebuffers long time seldom used slice. have big issue slice()
on bytebuffer
.
please see below code :
import java.io.unsupportedencodingexception; import java.nio.bytebuffer; import java.util.arrays; public class test12 { public static void main(string[] args) throws unsupportedencodingexception { bytebuffer original = bytebuffer.wrap("234567".getbytes("utf-8")); printbuffer("org: ",original); original.position(1); original.limit(original.limit()-2); printbuffer("org: ",original); bytebuffer sliced = original.slice(); printbuffer("slc: ",sliced); bytebuffer duplicated = original.duplicate(); printbuffer("dup: ",duplicated); bytebuffer compact = original.compact(); printbuffer("cmp: ",compact); } private static void printbuffer(string prefix,bytebuffer buff) { system.out.println(prefix+buff); system.out.println(prefix+arrays.tostring(arrays.copyofrange(buff.array(), buff.position(), buff.limit()))); } }
it results in
org: java.nio.heapbytebuffer[pos=0 lim=6 cap=6] org: [50, 51, 52, 53, 54, 55] org: java.nio.heapbytebuffer[pos=1 lim=4 cap=6] org: [51, 52, 53] slc: java.nio.heapbytebuffer[pos=0 lim=3 cap=3] slc: [50, 51, 52] dup: java.nio.heapbytebuffer[pos=1 lim=4 cap=6] dup: [51, 52, 53] cmp: java.nio.heapbytebuffer[pos=3 lim=6 cap=6] cmp: [53, 54, 55]
please see slc: value in above result. expect [51, 52, 53]
.
correct me if wrong. bug in java ?
i tested in java 7 , 8
from slice
method reference:
the new buffer's position will zero, capacity , limit number of bytes remaining in buffer, , mark undefined.
so although set position 1
works fine due documentation
Comments
Post a Comment