Kathir J Kathir J - 6 months ago 21
Java Question

convert portion of byte array values to String

I have loaded the entire file into a byte[] array

byte[] data = Files.readAllBytes(path);

Now i would like to get the first 120 characters as String and any string info from from index and to index...

Could you please let me know how to do it?

Thanks.

Answer

Sounds like you're just looking for this constructor:

String text = new String(data, 0, 120, StandardCharsets.UTF_8);

(Always specify the encoding explicitly when converting between binary and text forms.)