There is a UTF-8-encoded text file that reads a string with filereader and then converts the character set: Str = newstring (Str. getbytes (), "UTF-8"); the result is that most Chinese characters are displayed normally, but some Chinese characters are still displayed as question marks!
Java code
Public static list <string> getlines (string filename ){
List <string> lines = newarraylist <string> ();
Try {
Bufferedreader BR = new bufferedreader (New filereader (filename ));
String line = NULL;
While (line = Br. Readline ())! = NULL ){
Lines. Add (newstring (line. getbytes ("GBK"), "UTF-8 "));
}
BR. Close ();
} Catch (filenotfoundexception e ){
} Catch (ioexception e ){}
Return lines;
}
Public staticlist <string> getlines (string filename ){
List <string> lines = new arraylist <string> ();
Try {
Bufferedreader BR = new bufferedreader (newfilereader (filename ));
String line = NULL;
While (line = Br. Readline ())! = NULL ){
Lines. Add (newstring (line. getbytes ("GBK"), "UTF-8 "));
}
BR. Close ();
} Catch (filenotfoundexception e ){
} Catch (ioexception e ){}
Return lines;
}
When a file is read, it is decoded by the default OS Character Set GBK. I first use the default Character Set GBK encoding Str. getbytes ("GBK") should be restored to the byte sequence in the file, and then decoded by UTF-8, the generated string should be correct.
Why are some garbled characters in the results?
The problem is that when filereader reads a file, filereader inherits inputstreamreader, but does not implement the constructor with character set parameters in the parent class. Therefore, filereader can only be decoded according to the default Character Set of the system, then there is a loss of encoding in the process of UTF-8-> GBK-> UTF-8, resulting in the result cannot restore the original character.
The reason is clear, this problem is not difficult to solve, replace filereader with inputstreamreader, inputstreamreaderisr = new inputstreamreader (New fileinputstream (filename), "UTF-8 "); in this way, the file will be directly decoded with the UTF-8, no need to do the encoding conversion.
Java code
Public static list <string> getlines (string filename ){
List <string> lines = newarraylist <string> ();
Try {
Bufferedreader BR = new bufferedreader (New inputstreamreader (newfileinputstream (filename), "UTF-8 "));
String line = NULL;
While (line = Br. Readline ())! = NULL ){
Lines. Add (line );
}
BR. Close ();
} Catch (filenotfoundexception e ){
} Catch (ioexception e ){}
Return lines;
}