国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

JDK:java讀文件的一點見解

2019-11-18 15:29:50
字體:
來源:轉載
供稿:網友
    做開發的經常碰到文件的操作,非凡是文件的“讀”操作。在java中,讀文件有很多種方法,有FileReader、BufferReader等,當然,各種方法的效率是不一樣的,FileReader經BufferReader包裝后效率明顯提高,在個別時候,我們可以用java.nio包進行文件操作,如下:
    PRivate static String fileReader(File fileName) {
        String fileContent = null;
        FileInputStream fis = null;
        FileChannel fc = null;
        try {
            fis = new FileInputStream(fileName);
            // get a file channel
            fc = fis.getChannel();

            // create a ByteBuffer that is large enough
            // and read the contents of the file into it
            // test
            // System.out.println(fc.size());
            ByteBuffer bb = ByteBuffer.allocate((int) fc.size() + 1);

            fc.read(bb);
            bb.flip();

            // save the content of the file as a String
            // if we want to change the encode
            // we can directly add a second parameter here
            // which is of course more efficent

            // System.out.println(bb.capacity());
            fileContent = new String(bb.array());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //    release the FileChannel
            try {
                fc.close();
            } catch (Exception ex) {

            }
            try {
                fis.close();
            } catch (Exception ex) {

            }
        }

        // write out the contents of this file
        return fileContent;

    }
使用這種方法有個致命的弱點,當所讀文件較大時,將消耗大量內存,甚至發生OutOfMemory Error,而當文件較小時,使用該方法的效率就明顯高得多。

另外,歡迎大家到我的blog,更多經典文章等你來看http://blog.csdn.net/hdy007/ 

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南华县| 镇平县| 阿荣旗| 泗阳县| 驻马店市| 佛冈县| 曲周县| 油尖旺区| 胶州市| 肇庆市| 巧家县| 常德市| 中江县| 翼城县| 周宁县| 威远县| 汉源县| 象山县| 二手房| 宁明县| 即墨市| 台中市| 石首市| 五台县| 图木舒克市| 东城区| 甘南县| 余庆县| 正镶白旗| 济南市| 项城市| 岑巩县| 姚安县| 京山县| 双桥区| 美姑县| 梅河口市| 泸西县| 庄浪县| 玛多县| 灵寿县|