The first step: to first determine the source file encoding format:
Storing the file in the given character set can potentially store encoded information in the first three bytes of the file, so the basic principle is to read out the first three bytes of the file and determine the value of those bytes to be able to learn its encoded format. In fact, if the project running platform is the Chinese operating system, if these text files in the project, that is, developers can control the encoding of the text format, as long as the two common coding can be judged: GBK and UTF-8. Because the default encoding for Chinese Windows is GBK, the UTF-8 encoding format is generally only determined. For UTF-8 encoded text files, the first 3 byte values are-17,-69, and 65, so the code fragment that determines whether the encoding is UTF-8 is as follows:
File File = new file (path);
InputStream in= New Java.io.FileInputStream (file);
Byte[] B = new byte[3];
In.read (b);
In.close ();
if (b[0] = = -17 && b[1] = = -69 && b[2] = = -65)
System.out.println (file.getname () + ": Encoded as UTF-8");
else
System.out.println (file.getname () + ": May be GBK, or possibly other encoding");
Step two: Read the file stream in the specified encoding format
[Java] View plain copy private static string fortest (string file) throws IOException { file f = new file ( File); inputstreamreader read = new inputstreamreader ( New fileinputstream (f), "encoding format"); BufferedReader reader = new BufferedReader (Read); String line; string s = ""; while (line = reader.readline ()) { s = s+line; != null) } return s; }
Summary: is to adopt the following way:
File File = new file ("D:\\myeclipse\\ini\\config.properties");
FileInputStream in = new FileInputStream (file);
Byte[] B = new byte[3];
In.read (b);
String code = "GBK";
if (b[0] = = -17 && b[1] = = -69 && b[2] = = -65) {
code = "UTF-8";
}
InputStreamReader InputStreamReader = new InputStreamReader (in,code);
BufferedReader BufferedReader = new BufferedReader (inputstreamreader);
String str = bufferedreader.readline ();
String data = "";
while (str!= null) {
data = data + str+ "\ r \ n";
str = Bufferedreader.readline ();
}
In.close ();
Bufferedreader.close ();
SYSTEM.OUT.PRINTLN (code);
SYSTEM.OUT.PRINTLN (data);