-3

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.

Girish kumar
  • 735
  • 6
  • 8
  • 1
    I think the answer to your question will depend on the _encoding_ of your string. Some obtuse Chinese characters might take 4 bytes, while a base ASCII character might only take one byte. – Tim Biegeleisen Apr 18 '17 at 06:31

2 Answers2

0

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.

Community
  • 1
  • 1
Magesh
  • 221
  • 2
  • 10
  • [UTF-8](https://en.wikipedia.org/wiki/UTF-8) is not 1 byte per character. It's a variable length encoding and uses 1 to 4 bytes per character. – Jesper Apr 18 '17 at 07:31
-1

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);
        }
    }
Jay Smith
  • 2,331
  • 3
  • 16
  • 27