做開發的經常碰到文件的操作,非凡是文件的“讀”操作。在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);
// 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());