本地文件是在windows下使用记事本保存为utf-8格式文件中内容如下,第一行是回车键产生的空行:
你知道李白是谁吗
你知道我 是谁吗
你知道齐秦是谁吗
你知道芦苇吗
你知道蒹葭吗
你知道鳄鱼吗
你知道中国吗
你知道雪吗
你知道衣服吗
你知道馒头吗
package other;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReadFileTest {
public void test(){
File f = new File("E:/seleniumTest/3/20171108.txt");
FileInputStream fis;
String ch = "";
try {
fis = new FileInputStream(f);
byte[] b = new byte[1024];
int read = 0;
while((read = fis.read(b))> -1){
ch += new String(b,0,b.length);
}
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] all = ch.split("\r\n");
System.out.println(ch);
//输出是否相等
System.out.println(new String(all[0].getBytes()).equals("") );
//输出byte数组
System.out.println(Arrays.toString(all[0].getBytes()));
}
public static void main(String[] args) {
new ReadFileTest().test();
}
}
运行程序,输出结果:
false
[-17, -69, -65]
同样是空行为什么不相等?为什么getBytes()得到的是负数?这其中我也还没搞清楚,当前最想解决的是如何让它输出true
原因:
使用windows记事本另存为utf-8文件,该文件是带BOM的,Byte Order Mark
我的解决方法:
使用NotePad++或其他文本编辑器将本地文件保存为无BOM格式的utf-8格式