In general, you cannot.
Having a byte order mark is a very strong sign that the file you are reading is Unicode. If you expect a text file and the first four bytes you get:
0x00, 0x00, 0xfe, 0xff
But what else? If the bytes you receive are something other than one of these five patterns, then you cannot say for sure that your file is or is not UTF-8.
In fact, any text document containing only ASCII characters from 0x00 to 0x7f is a valid UTF-8 document and is also a simple ASCII document.
There are heuristics that may try to conclude whether the document was encoded, for example, ISO-8859-1 or UTF-8, or CP1252, but, in general, the first two, three or four bytes of a file are not enough to say, is whether what you are watching is definitely UTF-8.
source share