UTF-8文件本身分为带有BOM和NO BOM的文件格式,即用记事本对UTF-8文件打开后再另存为UTF-8时会在文件中插入一个BOM。
从而导致读取时出现乱码。
解决方式
/**
* @name UnicodeReader
* @Date 2010-06-23
* @param InputStream is :输入流
* @param String encoding :默认字符集
* @return InputStreamReader
*
*/
protected static InputStreamReader UnicodeReader(InputStream is,
String encoding) throws IOException
{
final int BOM_SIZE = 4;
byte bom[] = new byte[BOM_SIZE];
int n, unread;
if (is == null)
return null;
PushbackInputStream internalIn = new PushbackInputStream(is, BOM_SIZE);
n = internalIn.read(bom, 0, bom.length);
if ((bom[0] == (byte) 0x00) && (bom[1] == (byte) 0x00)
&& (bom[2] == (byte) 0xFE) && (bom[3] == (byte) 0xFF))
{
encoding = "UTF-32BE";
unread = n - 4;
}
else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)
&& (bom[2] == (byte) 0x00) && (bom[3] == (byte) 0x00))
{
encoding = "UTF-32LE";
unread = n - 4;
}
else if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB)
&& (bom[2] == (byte) 0xBF))
{
encoding = "UTF-8";
unread = n - 3;
}
else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF))
{
encoding = "UTF-16BE";
unread = n - 2;
}
else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE))
{
encoding = "UTF-16LE";
unread = n - 2;
}
else
{
// Unicode BOM mark not found, unread all bytes
if (encoding.equals(""))
{
encoding = "UTF-8";
}
unread = n;
}
if (unread > 0)
internalIn.unread(bom, (n - unread), unread);
return (new InputStreamReader(internalIn, encoding));
}
public static void main(String[] args) throws IOException
{
File f = new File("D://G-mybackup//sametime//index.ini");
FileInputStream in = new FileInputStream(f);
// 指定读取文件时以UTF-8的格式读取
BufferedReader br = new BufferedReader(UnicodeReader(in,"UTF-8"));
String line = br.readLine();
while (line != null)
{
System.out.println(line);
line = br.readLine();
}
}