1 import java.io.BufferedReader; 2 import java.io.File; 3 import java.io.FileReader; 4 import java.io.IOException; 5 6 public class ReadFromFile { 7 8 9 10 public static void main(String[] args) { 11 //文件绝对路径 12 String fileName="C:\\Users\\liujun\\Desktop\\platform_machine"; 13 14 readFileByLines(fileName); 15 16 } 17 18 /** 19 * 以行为单位读取文件,常用于读面向行的格式化文件 20 */ 21 public static void readFileByLines(String fileName) { 22 23 File file = new File(fileName); 24 File[] tempList = file.listFiles(); 25 // System.out.println("该目录下对象个数:"+tempList.length); 26 27 for (int i = 0; i < tempList.length; i++) { 28 if (tempList[i].isFile()) { 29 //System.out.println("文 件:"+tempList[i]); 30 BufferedReader reader = null; 31 try { 32 //System.out.println("以行为单位读取文件内容,一次读一整行:"); 33 //读取指定文件夹下的每一个文件 34 reader = new BufferedReader(new FileReader(tempList[i])); 35 36 String tempString = null; 37 int line = 1; 38 // 一次读入一行,直到读入null为文件结束 39 while ((tempString = reader.readLine()) != null) { 40 // 判断包含ERROR的打印出来 41 if(tempString.indexOf("[ERROR] (JdbcAgent.java :398)---function update [ INSERT")== -1){ 42 43 }else { 44 //截取一行的开始位置 45 String a="'010002'"; 46 //截取一行的结束位置 47 String b="]"; 48 //打印每个文件的第几列和截取的数据 49 //System.out.println("line " + line + ": " + tempString.substring(tempString.indexOf(a),tempString.lastIndexOf(b) )); 50 //打印每行截取的数据 51 System.out.println(tempString.substring(tempString.indexOf(a),tempString.lastIndexOf(b))); 52 } 53 line++; 54 } 55 reader.close(); 56 } catch (IOException e) { 57 e.printStackTrace(); 58 } finally { 59 if (reader != null) { 60 try { 61 reader.close(); 62 } catch (IOException e1) { 63 } 64 } 65 } 66 67 } 68 //判断是否还包含文件夹 69 if (tempList[i].isDirectory()) { 70 System.out.println("文件夹:"+tempList[i]); 71 } 72 } 73 74 } 75 76 77 }