读取文件中的换行符不等于空

来源:互联网 发布:可口可乐的销售数据 编辑:程序博客网 时间:2024/05/28 15:08
本地文件是在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 blocke.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格式