It's inherently not simple. There's no way of knowing for sure, although you can take a reasonably good guess in most cases.
Things you might like to do:
- Look for known magic numbers in binary signatures
- Look for the Unicode byte-order-mark at the start of the file
- If the file is regularly 00 xx 00 xx 00 xx (for arbitrary xx) or vice versa, that's quite possibly UTF-16
- Otherwise, look for 0s in the file; a file with a 0 in is unlikely to be a single-byte-encoding text file.
But it's all heuristic - it's quite possible to have a file which is a valid text file and a valid image file, for example. It would probably be nonsense as a text file, but legitimate in some encoding or other...