java 讀取檔案——按照行取出(使用BufferedReader和一次將資料儲存到記憶體兩種實現方式),javabufferedreader

來源:互聯網
上載者:User

java 讀取檔案——按照行取出(使用BufferedReader和一次將資料儲存到記憶體兩種實現方式),javabufferedreader

1、實現目標

  讀取檔案,將檔案中的資料一行行的取出。

2、代碼實現

1)、方式1:

  通過BufferedReader的readLine()方法。

/**     * 功能:Java讀取txt檔案的內容 步驟:1:先獲得檔案控制代碼 2:獲得檔案控制代碼當做是輸入一個位元組碼流,需要對這個輸入資料流進行讀取     * 3:讀取到輸入資料流後,需要讀取產生位元組流 4:一行一行的輸出。readline()。 備忘:需要考慮的是異常情況     *      * @param filePath     *            檔案路徑[到達檔案:如: D:\aa.txt]     * @return 將這個檔案按照每一行切割成數組存放到list中。     */    public static List<String> readTxtFileIntoStringArrList(String filePath)    {        List<String> list = new ArrayList<String>();        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)                {                    list.add(lineTxt);                }                bufferedReader.close();                read.close();            }            else            {                System.out.println("找不到指定的檔案");            }        }        catch (Exception e)        {            System.out.println("讀取檔案內容出錯");            e.printStackTrace();        }        return list;    }

2)、方式2

  通過檔案byte數組暫存檔案中內容,將其轉換為String資料,再按照 “斷行符號換行” 進行分割。

/**     * 讀取filePath的檔案,將檔案中的資料按照行讀取到String數組中     * @param filePath    檔案的路徑     * @return            檔案中一行一行的資料     */    public static String[] readToString(String filePath)    {        File file = new File(filePath);        Long filelength = file.length(); // 擷取檔案長度        byte[] filecontent = new byte[filelength.intValue()];        try        {            FileInputStream in = new FileInputStream(file);            in.read(filecontent);            in.close();        } catch (FileNotFoundException e)        {            e.printStackTrace();        } catch (IOException e)        {            e.printStackTrace();        }                String[] fileContentArr = new String(filecontent).split("\r\n");                return fileContentArr;// 返迴文件內容,預設編碼    }

3)、測試

public static void main(String[] args)    {                List<String> stringList = readTxtFileIntoStringArrList("C:\\soft\\java\\tomcat\\apache-tomcat-7.0.40\\webapps\\appDataGenerate\\log4j\\lepai_recognize_cache.log");                System.out.println("-------使用BufferedReader讀取-----------");        for(String str : stringList)        {            System.out.println(str);        }                System.out.println("\n---------使用byte直接緩衝整個檔案到記憶體----------------");                String[] stringArr = readToString("C:\\soft\\java\\tomcat\\apache-tomcat-7.0.40\\webapps\\appDataGenerate\\log4j\\lepai_recognize_cache.log");        for(int i = 0 ; i < stringArr.length ; i ++)        {            System.out.println(stringArr[i]);        }                    }

結果:

-------使用BufferedReader讀取-----------[2015-11-30 13:21:28] [RecognizeCache] [INFO] : RecogizeCache init[2015-11-30 13:21:28] [RecognizeCache] [INFO] : RecogizeCache init[2015-11-30 13:21:28] [RecognizeCache] [INFO] : RecogizeCache init[2015-11-30 13:21:28] [RecognizeCache] [INFO] : RecogizeCache init[2015-12-01 14:52:04] [RecognizeCache] [INFO] : 讀取檔案:4209bad42de0f6e55c0daf0bd24b635a.txt---------使用byte直接緩衝整個檔案到記憶體----------------[2015-11-30 13:21:28] [RecognizeCache] [INFO] : RecogizeCache init[2015-11-30 13:21:28] [RecognizeCache] [INFO] : RecogizeCache init[2015-11-30 13:21:28] [RecognizeCache] [INFO] : RecogizeCache init[2015-11-30 13:21:28] [RecognizeCache] [INFO] : RecogizeCache init[2015-12-01 14:52:04] [RecognizeCache] [INFO] : 讀取檔案:4209bad42de0f6e55c0daf0bd24b635a.txt

3、比較

  方式1是將檔案的一部分或全部資料讀取出來用BufferReader緩衝起來,需要再沖緩衝中取資料,這樣比要得時候去檔案中讀取要快一些。

  方式2是一次把文本的原始內容直接讀取到記憶體中再做處理(暫時不考慮記憶體大小),這樣做效率也會提高。同時,可以處理當你使用第1方式用readLine()方法時,檔案又有線程在不斷的向檔案中寫資料【只處理現在已經在檔案中的資料】。另外,用readline()之類的方法,可能需要反覆訪問檔案,而且每次readline()都會調用編碼轉換,降低了速度,所以,在已知編碼的情況下,按位元組流方式先將檔案都讀入記憶體,再一次性編碼轉換是最快的方式。

  有錯誤的希望大牛不吝賜教。 想瞭解一下,

  1、通過ftp取一個檔案到本地,我如何判斷對方的檔案是否已經寫完了。

  2、當我使用上面的BufferedReader的readLine()方法一行行讀取檔案的時候,我還向檔案中添加資料,會不會出現檔案讀取結束不了的情況。

源碼下載:

https://github.com/zcr1007391008/demo 的TestReadAllFileToMemory。

  致謝:感謝您的閱讀!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.