I have a tasks list object that I repeat and add each task object to StringBuilder , and then a new line, as shown below. Now I will continue to add the task object to the same string builder until it reaches the limit of 60,000 bytes. As soon as it reaches the limit, I will fill this line as a value on the map, and the key will have a file name with an incremental index. And then I will build a reset line constructor and another thing and repeat this process again.
So, if I have a large tasks object, then I will split it into several string objects, the size of which should be less than 60,000 bytes.
I got the code below, but I always see that the value on the card is larger than 60,000 bytes. Something is wrong, what am I doing? I also populate the HashMap in two different places - one if the limit is reached, and the other if the limit is not reached.
public void populate(final List<Task> tasks) { Map<String, String> holder = new HashMap<>(); int size = 0; int index = 0; StringBuilder sb = new StringBuilder(); for (Task task : tasks) { sb.append(task).append(System.getProperty("line.separator")); size = sb.toString().getBytes(StandardCharsets.UTF_8).length; if (size > 60000) { String fileName = "tasks_info_" + index + ".txt"; holder.put(fileName, sb.toString()); index++; sb = new StringBuilder(); size = 0; } }
Note. If each Task object is larger than 60000 bytes , I will immediately delete this object and move on to the next entry. But in reality this will not happen.
Update:
public void populate(final List<Task> tasks, final long timestamp) { Map<String, String> holder = new HashMap<>(); int size = 0; int index = 0; int nl = System.getProperty("line.separator").getBytes(StandardCharsets.UTF_8).length; StringBuilder sb = new StringBuilder();
source share