Java後台按行讀取txt檔案

來源:互聯網
上載者:User

標籤:line   檔案控制代碼   資訊   color   exception   nbsp   指定   lis   ram   

java讀取txt檔案內容。可以作如下理解:

  1. 首先獲得一個檔案控制代碼。File file = new File(); file即為檔案控制代碼。兩人之間連通電話網路了。接下來可以開始打電話了。

  2. 通過這條線路讀取甲方的資訊:new FileInputStream(file) 目前這個資訊已經讀進來記憶體當中了。接下來需要解讀成乙方可以理解的東西

  3. 既然你使用了FileInputStream()。那麼對應的需要使用InputStreamReader()這個方法進行解讀剛才裝進來記憶體當中的資料

  4. 解讀完成後要輸出呀。那當然要轉換成IO可以識別的資料呀。那就需要調用位元組碼讀取的方法BufferedReader()。同時使用bufferedReader()的readline()方法讀取txt檔案中的每一行資料哈。

    package com.campu; import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.InputStreamReader;import java.io.Reader; /** * @author 碼農小江 * H20121012.java * 2012-10-12下午11:40:21 */public class H20121012 {    /**     * 功能:Java讀取txt檔案的內容     * 步驟:1:先獲得檔案控制代碼     * 2:獲得檔案控制代碼當做是輸入一個位元組碼流,需要對這個輸入資料流進行讀取     * 3:讀取到輸入資料流後,需要讀取產生位元組流     * 4:一行一行的輸出。readline()。     * 備忘:需要考慮的是異常情況     * @param filePath     */    public static void readTxtFile(String filePath){        try {                String encoding="GBK";                File file=new File(filePath);                if(file.isFile() && file.exists()){ //判斷檔案是否存在                    InputStreamReader read = new InputStreamReader(                    new FileInputStream(file),encoding);//考慮到編碼格式                    BufferedReader bufferedReader = new BufferedReader(read);                    String lineTxt = null;                    while((lineTxt = bufferedReader.readLine()) != null){                        System.out.println(lineTxt);                    }                    read.close();        }else{            System.out.println("找不到指定的檔案");        }        } catch (Exception e) {            System.out.println("讀取檔案內容出錯");            e.printStackTrace();        }         }         public static void main(String argv[]){        String filePath = "L:\\Apache\\htdocs\\res\\20121012.txt";//      "res/";        readTxtFile(filePath);    }           }

     

Java後台按行讀取txt檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.