I need a chop off a string if the size exceeds more than 1mb.
How can I do it in java?? Basically anything above 1mb has to be chopped off and I should get a string which is exactly of 1mb size or lesser than that.
I need a chop off a string if the size exceeds more than 1mb.
How can I do it in java?? Basically anything above 1mb has to be chopped off and I should get a string which is exactly of 1mb size or lesser than that.
Java consider 2bytes for a character. But it still varies based on the encoding used. Refer the link for more detail
Consider if you are using UTF-8 encoding, which takes 1 bytes per character. You can chop of for every 1048576 bytes which is 1 MB.
Try this code for your string:
public static void main(String[] args) {
// Get length of String in bytes
String string = "long string";
long sizeInBytes = string.getBytes().length;
int oneMb=1024*1024;
if (sizeInBytes>oneMb) {
String string1Mb=string.substring(0, oneMb);
}
}