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