java以行讀取txt文本內容

package web.util;
import java.io.BufferedReader;  
import java.io.File;  
import java.io.FileReader;  
import java.io.IOException; 
/**
 * 
 *  #(c) IFlytek bz_szrx <br/>
 *
 *  版本說明: $id:$ <br/>
 *
 *  功能說明: 按行讀取text文件內同
 * 
 *  <br/>創建說明: 2015-1-9 下午01:33:59 (☆_☆)  創建文件<br/>
 * 
 *  修改歷史:<br/>
 *
 */
public class testRead {
 
   public testRead() {  
   }  
   static testRead read=new testRead();  
 
   /** 
    * @param args 
    */  
   public static void main(String[] args) {  
    //獲取classes文件路徑
       String path=read.getClass().getResource("/").getPath();  
       System.out.println(java.io.File.separator+"---"+path);
       //java.io.File.separator  可以平臺分割  
       readFileByLines( path+java.io.File.separator+"lhpbzk.txt");  
   }  
   /**
    *  功能描述:一行爲單位讀取內容
    *
    * @author (☆_☆)  2015-1-9 下午01:35:13
    * 
    * @param fileName
    */
   public static void readFileByLines(String fileName) {  
       File file = new File(fileName);  
       BufferedReader reader = null;  
       try {  
           System.out.println("一次讀一整行:");  
           reader = new BufferedReader(new FileReader(file));  
           String tempString = null;  
           int line = 1;  
           // 一次讀入一行,直到讀入null爲文件結束  
           while ((tempString = reader.readLine()) != null) {  
               // 顯示行號  
               System.out.println("line " + line + ": " + tempString);  
               line++;  
           }  
           reader.close();  
       } catch (IOException e) {  
           e.printStackTrace();  
       } finally {  
           if (reader != null) {  
               try {  
                   reader.close();  
               } catch (IOException e1) {  
               }  
           }  
       }  
   }  
 


輸出結果如下:





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章