使用BufferedReader中的readLine方法可以按行读取文件内容,返回空表示读取结束。今天读取文件的时候,发现最终读出来的文件缺少数据,然后发下源文件中有几个空行,但是代码里已经写了readLine判空了呀,为啥还不行呢?问题就出在判空这里了。。。
上代码
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\111.txt"), "UTF-8"));
while (true) {
String line= reader.readLine();
if (StringUtils.isBlank(line)){// 注意看这里
break;
}
JSONObject jsonObject = JSONObject.parseObject(line);
System.out.println(jsonObject);
}
reader.close();
}
注意看第5行判空那里,我直接用工具类判空了,但是StringUtils.isBlank()方法是判断字符串是否为null、是否为""、是否为空字符串(引号中间有空格)" ",以上情景都会返回true。而读取源文件的空行时line返回的是""不是null,所以读到空行后 直接就跳出循环了导致后面的数据没有读到。
修改后
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\111.txt"), "UTF-8"));
while (true) {
String line= reader.readLine();
if (null == line){ // 当返回null的时候在跳出
break;
}
JSONObject jsonObject = JSONObject.parseObject(line);
System.out.println(jsonObject);
}
reader.close();
}
把判空逻辑修改下就可以读到完全的数据了。
日常记录下,readLine只有返回null的时候才表示文件读取完,而不是"".