讀取文件有多種方式,基于傳統(tǒng)的輸入流方式或基于nio的Buffer緩沖對(duì)象和管道讀取方式甚至非常快速的內(nèi)存映射讀取文件。
站在用戶(hù)的角度思考問(wèn)題,與客戶(hù)深入溝通,找到岳普湖網(wǎng)站設(shè)計(jì)與岳普湖網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗(yàn),讓設(shè)計(jì)與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個(gè)性化、用戶(hù)體驗(yàn)好的作品,建站類(lèi)型包括:網(wǎng)站建設(shè)、成都網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣、空間域名、網(wǎng)站空間、企業(yè)郵箱。業(yè)務(wù)覆蓋岳普湖地區(qū)。
java中四種讀取文件方式:
1、RandomAccessFile:隨機(jī)讀取,比較慢優(yōu)點(diǎn)就是該類(lèi)可讀可寫(xiě)可操作文件指針
2、FileInputStream:io普通輸入流方式,速度效率一般
3、Buffer緩沖讀取:基于nio Buffer和FileChannel讀取,速度較快
4、內(nèi)存映射讀?。夯贛appedByteBuffer,速度最快
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)注創(chuàng)新互聯(lián)其它相關(guān)文章!