Completely solve Android read Chinese txt garbled (automatically determine the document type and transcoding

Source: Internet
Author: User

Original: http://blog.csdn.net/handsomedylan/article/details/6138400

public string Convertcodeandgettext (string str_filepath) {//transcoding

File File = new file (Str_filepath);
BufferedReader reader;
String text = "";
try {
FileReader F_reader = new FileReader (file);
BufferedReader reader = new BufferedReader (F_reader);
FileInputStream fis = new FileInputStream (file);
Bufferedinputstream in = new Bufferedinputstream (FIS);
In.mark (4);
byte[] first3bytes = new Byte[3];
In.read (first3bytes);//finds the first three bytes of a document and automatically determines the document type.
In.reset ();
if (first3bytes[0] = = (byte) 0xEF && first3bytes[1] = = (byte) 0xBB
&& first3bytes[2] = = (byte) 0xBF) {//Utf-8

reader = new BufferedReader (new InputStreamReader (in, "Utf-8"));

} else if (first3bytes[0] = = (byte) 0xFF
&& first3bytes[1] = = (byte) 0xFE) {

reader = new BufferedReader (
New InputStreamReader (In, "Unicode"));
} else if (first3bytes[0] = = (byte) 0xFE
&& first3bytes[1] = = (byte) 0xFF) {

reader = new BufferedReader (new InputStreamReader (in,
"Utf-16be"));
} else if (first3bytes[0] = = (byte) 0xFF
&& first3bytes[1] = = (byte) 0xFF) {

reader = new BufferedReader (new InputStreamReader (in,
"Utf-16le"));
} else {

reader = new BufferedReader (new InputStreamReader (in, "GBK"));
}
String str = reader.readline ();

while (str! = null) {
Text = text + str + "/n";
str = Reader.readline ();

}
Reader.close ();

} catch (FileNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace ();
}
return text;
}
Code is not difficult, feel useful can be a top.

Completely solve Android read Chinese txt garbled (automatically determine the document type and transcoding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.