您好,登錄后才能下訂單哦!
讀取文件有多種方式,基于傳統(tǒng)的輸入流方式或基于nio的Buffer緩沖對(duì)象和管道讀取方式甚至非常快速的內(nèi)存映射讀取文件。
java中四種讀取文件方式:
1、RandomAccessFile:隨機(jī)讀取,比較慢優(yōu)點(diǎn)就是該類(lèi)可讀可寫(xiě)可操作文件指針
2、FileInputStream:io普通輸入流方式,速度效率一般
3、Buffer緩沖讀?。夯趎io Buffer和FileChannel讀取,速度較快
4、內(nèi)存映射讀取:基于MappedByteBuffer,速度最快
RandomAccessFile讀取
//RandomAccessFile類(lèi)的核心在于其既能讀又能寫(xiě) public void useRandomAccessFileTest() throws Exception { RandomAccessFile randomAccessFile = new RandomAccessFile(new File("e:/nio/test.txt"), "r"); byte[] bytes = new byte[1024]; int len = 0; while ((len = randomAccessFile.read(bytes)) != -1) { System.out.println(new String(bytes, 0, len, "gbk")); } randomAccessFile.close(); }
FielInputStream讀取
//使用FileInputStream文件輸入流,比較中規(guī)中矩的一種方式,傳統(tǒng)阻塞IO操作。 public void testFielInputStreamTest() throws Exception { FileInputStream inputStream = new FileInputStream(new File("e:/nio/test.txt")); // 使用輸入流讀取文件,以下代碼塊幾乎就是模板代碼 byte[] bytes = new byte[1024]; int len = 0; while ((len = inputStream.read(bytes)) != -1) {// 如果有數(shù)據(jù)就一直讀寫(xiě),否則就退出循環(huán)體,關(guān)閉流資源。 System.out.println(new String(bytes, 0, len, "gbk")); } inputStream.close(); }
Buffer緩沖對(duì)象讀取
// nio 讀取 public void testBufferChannel() throws Exception { FileInputStream inputStream = new FileInputStream(new File("e:/nio/test.txt")); FileChannel fileChannel = inputStream.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); // 以下代碼也幾乎是Buffer和Channle的標(biāo)準(zhǔn)讀寫(xiě)操作。 while (true) { buffer.clear(); int result = fileChannel.read(buffer); buffer.flip(); if (result == -1) { break; } System.out.println(new String(buffer.array(), 0, result, "gbk")); } inputStream.close(); }
內(nèi)存映射讀取
public void testmappedByteBuffer() throws Exception { FileInputStream inputStream = new FileInputStream(new File("e:/nio/test.txt")); FileOutputStream outputStream = new FileOutputStream(new File("e:/nio/testcopy.txt"),true); FileChannel inChannel = inputStream.getChannel(); FileChannel outChannel = outputStream.getChannel(); System.out.println(inChannel.size()); MappedByteBuffer mappedByteBuffer = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size()); System.out.println(mappedByteBuffer.limit()); System.out.println(mappedByteBuffer.position()); mappedByteBuffer.flip(); outChannel.write(mappedByteBuffer); outChannel.close(); inChannel.close(); outputStream.close(); inputStream.close(); } //基于內(nèi)存映射這種方式,這么寫(xiě)好像有問(wèn)題。 MappedByteBuffer和RandomAcessFile這兩個(gè)類(lèi)要單獨(dú)重點(diǎn)研究一下。 //TODO 大文件讀取
以上就是java中如何讀取文件?的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注億速云其它相關(guān)文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。