Chinaunix首页 | 论坛 | 博客
  • 博客访问: 805921
  • 博文数量: 780
  • 博客积分: 7000
  • 博客等级: 少将
  • 技术积分: 5010
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-12 09:11
文章分类

全部博文(780)

文章存档

2011年(1)

2008年(779)

我的朋友
最近访客

分类:

2008-09-12 09:12:00

    做开发的经常碰到文件的操作,特别是文件的“读”操作。在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/ 
【责编:Peng】

--------------------next---------------------

阅读(461) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~