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 }