If the size of the array is greater than 128, it is necessary to divide it into arrays of 128 bytes each.

private List<byte[]> getBytesList(String str) { byte[] bytes = str.getBytes(); List<byte[]> bytesList = new ArrayList<>(); if (bytes.length < 128) { bytesList.add(bytes); } else { } return bytesList; } 

    2 answers 2

    Very interesting task, here I suggest this option.

    Update

    The previous version worked with English. characters of 1 byte, the new version of the code works with any. Accordingly, if you need to decompose an Object, you can change the received parameter to Object in the getList method, get the bytes in str_b from Object and send it on a trip using the method.

      package demo; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { String str = "Arguments: Привет [-PcmdLineArgs=, Привет -PjvmLineArgs=, Привет -c, /home/ufo/NetBeansПриветProjects/Demo/settings.gradle]"; System.out.println("str byte len = " + str.getBytes().length); for(byte[] item : getList(str, 12)){ // Debug System.out.println("item len = " + item.length); System.out.println(new String(item, StandardCharsets.UTF_8)); } } // Метод getList(String, int) принимает на вход 2 параметра: // 1. Строка // 2. Размер массива static List<byte[]> getList(String str, int len) { List<byte[]> list = new ArrayList<>(); byte[] str_b = str.getBytes(); int count = (int)Math.ceil((double)str_b.length / len); System.out.println("count = " + count); int start_position = 0; int end_position = len; for(int i = 1; i <= count; i++) { //Примечание: end_position - Этот индекс может находиться вне массива. list.add(Arrays.copyOfRange(str_b, start_position, end_position)); start_position += len; end_position = start_position + len; } return list; } } 
    • Thanks for the decision. - hmeli7
    • I wonder why 12? And yes, the number of characters does not match the number of bytes. - default locale
    • @ hmeli7 If this answer solves your problem, then mark it as a solution. - default locale
    • 12 we set the size of the array - hmeli7
    • Maybe even tell me how to be if we accept Object as input. As I understand it, we need to convert it into a byte array: ByteArrayOutputStream baos = new ByteArrayOutputStream (); ObjectOutput out = null; byte [] bytes = null; try {out = new ObjectOutputStream (baos); out.writeObject (object); out.flush (); bytes = bos.toByteArray (); } finally {baos.close (); } - hmeli7

    Create a new array of 128 elements and copy them. Keep the counter how many bytes counted and if the “common bytes” - “saved bytes” are more than 128 then repeat.