At first, the ASCII encoding was used to read the text data, to simulate reading the binary data, but found that if the character encoding was greater than 127, it would only get a value less than 128, equivalent to 128, so the ASCII encoding would not work.
Keep looking and find an article in codeproejct.com "Reading and writing Binary Files Using JScript", which is exactly what I need.
Actually, it's simple, is to change the code, use 437, this is the IBM extended ASCII encoding, the highest bit of ASCII encoding is also used to extend the character set characters from 128 to 256, and the character data read using this character set is equivalent to the original binary data.
Once the barrier is resolved, it is necessary to start identifying the encoding of the file, by using the ADODB.stream object to read the beginning two bytes of the file, and then to determine what the file encoding is based on the two bytes.
UTF-8 files with a BOM, then the first two bytes is 0xEF, 0xBB, and then, for example, the beginning of the Unicode file two bytes is 0xFF, 0xFE, which is the basis for judging file encoding.
It should be noted that when ADODB.stream read characters, not one by one corresponding, that is, if the binary data is 0xEF, read the characters after charCodeAt, not 0xFE, but another value, the corresponding table can be found in the article mentioned above.
Program code:
Copy Code code as follows:
function checkencoding (filename) {
var stream = new ActiveXObject ("ADODB. Stream ");
Stream. Mode = 3;
Stream. Type = 2;
Stream. Open ();
Stream. Charset = "437";
Stream. LoadFromFile (filename);
var BOM = Escape (stream. ReadText (2));
Switch (BOM) {
0XEF,0XBB => UTF-8
Case "%u2229%u2557":
encoding = "UTF-8";
Break
0xff,0xfe => Unicode
Case "%a0%u25a0":
0xfe,0xff => Unicode Big endian
Case "%U25A0%A0":
encoding = "Unicode";
Break
Use GBK If you don't know how to handle Chinese correctly in most cases
Default
encoding = "GBK";
Break
}
Stream. Close ();
Delete stream;
stream = null;
return encoding;
}
In this way, the encoding of the file can be obtained by calling the Checkencoding function when it is needed.
I hope this article is of some help to you.