java 读取文件有空行的代码如下:
package com.tl.utils; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; public class FileOperator { public static void readLocalFile(String filePath){ BufferedReader br=null; try { FileInputStream fis=new FileInputStream(filePath); InputStreamReader isr=new InputStreamReader(fis,"utf-8"); br=new BufferedReader(isr); String tempLine=null; while((tempLine=br.readLine())!=null){ tempLine=tempLine.trim(); System.out.println(tempLine); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ if(br!=null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String[] args) { String filePath="student.txt"; readLocalFile(filePath); } }运行结果如下: 很显然文件末行多读出了一个空行,加一个行计数器就可以解决这个问题
package com.tl.utils; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; public class FileOperator { public static String readLocalFile(String filePath){ BufferedReader br=null; StringBuilder stringBuilder=new StringBuilder(); try { FileInputStream fis=new FileInputStream(filePath); InputStreamReader isr=new InputStreamReader(fis,"utf-8"); br=new BufferedReader(isr); String tempLine=null; //定义行计数器 int line_counter=0; while((tempLine=br.readLine())!=null){ //去除左右空格 tempLine=tempLine.trim(); //实现逻辑:第二行才开始每一行的行首加换行。 if(line_counter>0){ stringBuilder.append("\n"); } stringBuilder.append(tempLine); line_counter++; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ if(br!=null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return stringBuilder.toString(); } public static void main(String[] args) { String filePath="student.txt"; String result=readLocalFile(filePath); System.out.println(result); } }