title: How can I check whether a byte array contains a Unicode string in Java?
body: <p>Given a byte array that is either a UTF-8 encoded string or arbitrary binary data, what approaches can be used <strong>in Java</strong> to determine which it is?</p>
  
  <p>The array may be generated by code similar to:</p>
  
  <pre><code>byte[] utf8 = "Hello World".getBytes("UTF-8");
  </code></pre>
  
  <p>Alternatively it may have been generated by code similar to:</p>
  
  <pre><code>byte[] messageContent = new byte[256];
  for (int i = 0; i &lt; messageContent.length; i++) {
      messageContent[i] = (byte) i;
  }
  </code></pre>
  
  <p>The key point is that we don't know what the array contains but need to find out in order to fill in the following function:</p>
  
  <pre><code>public final String getString(final byte[] dataToProcess) {
      // Determine whether dataToProcess contains arbitrary data or a UTF-8 encoded string
      // If dataToProcess contains arbitrary data then we will BASE64 encode it and return.
      // If dataToProcess contains an encoded string then we will decode it and return.
  }
  </code></pre>
  
  <p>How would this be extended to also cover UTF-16 or other encoding mechanisms?</p>