title: What is the best way to get the size of text in bytes in Java?
body: <p>I have implemented a cryptographic algorithm in Java. Now, I want to measure the size of the message before and after encryption in bytes.</p>
  
  <p>How to get the size of the text in bytes?</p>
  
  <p>For example, if I have a simple text <code>Hi! I am alphanumeric (8÷4=2)</code></p>
  
  <p>I have tried my best but can't find a good solution.</p>
  
  <pre><code>String temp = "Hi! I am alphanumeric (8÷4=2)"
  temp.length() // this works because in ASCII every char takes one byte
  
  // and in java every char in String takes two bytes so multiply by 2
  temp.length() * 2
  
  // also String.getBytes().length and getBytes("UTF-8").length
  // returns same result
  </code></pre>
  
  <p>But in my case after decryption of message the chars becomes the mixture of ASCII and Unicode.</p>
  
  <p>e.g. <code>QÂʫP†ǒ!‡˜q‡Úy¦\dƒὥì£‰ὥ</code></p>
  
  <p>Upper methods returns the <code>length</code> or <code>length * 2</code></p>
  
  <p>But I want to calculate the actual bytes (not in JVM). For example the char <code>a</code> takes one byte in general and Unicode <code>™</code> for example takes two bytes.</p>
  
  <p>So how to implement this technique in Java?</p>
  
  <p>I want some this likes the technique used in this website <a href="http://bytesizematters.com/" rel="nofollow noreferrer">http://bytesizematters.com/</a></p>
  
  <p>It gives me <code>26 bytes</code> for this text <code>QÂʫP†ǒ!‡˜q‡Úy¦\dƒὥì£‰ὥ</code> although the length of text is 22. </p>