最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java讀取文件的幾種方式詳細總結

 更新時間:2023年08月18日 09:14:11   作者:C3Stones  
這篇文章主要給大家介紹了關于Java讀取文件的幾種方式,文中通過代碼示例將幾種方式介紹的非常詳細,對大家學習或者使用Java具有一定的參考學習價值,需要的朋友可以參考下

1. 使用流讀取文件

public static void stream() {
    String fileName = "D:\\test.txt";
    final String CHARSET_NAME = "UTF-8";
    List<String> content = new ArrayList<>();
    try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), CHARSET_NAME))) {
        String line;
        while ((line = br.readLine()) != null) {
            content.add(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
//        content.forEach(System.out::println);
    System.out.println(content.size());
}

2. 使用JDK1.7提供的NIO讀取文件(適用于小文件)

public static void nioOfJDK7() {
    String fileName = "D:\\test.txt";
    final String CHARSET_NAME = "UTF-8";
    List<String> content = new ArrayList<>(0);
    try {
        content = Files.readAllLines(Paths.get(fileName), Charset.forName(CHARSET_NAME));
    } catch (Exception e) {
        e.printStackTrace();
    }
//        content.forEach(System.out::println);
    System.out.println(content.size());
}

3. 使用JDK1.7提供的NIO讀取文件(適用于大文件)

public static void streamOfJDK7() {
    String fileName = "D:\\test.txt";
    final String CHARSET_NAME = "UTF-8";
    List<String> content = new ArrayList<>();
    try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName), Charset.forName(CHARSET_NAME))) {
        String line;
        while ((line = br.readLine()) != null) {
            content.add(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
//        content.forEach(System.out::println);
    System.out.println(content.size());
}

4. 使用JDK1.4提供的NIO讀取文件(適用于超大文件)

public static void nioOfJDK4() {
    String fileName = "D:\\test.txt";
    final String CHARSET_NAME = "UTF-8";
    final int ASCII_LF = 10; // 換行符
    final int ASCII_CR = 13; // 回車符
    List<String> content = new ArrayList<>();
    try (FileChannel fileChannel = new RandomAccessFile(fileName, "r").getChannel()) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 100);
        byte[] lineByte;
        byte[] temp = new byte[0];
        while (fileChannel.read(byteBuffer) != -1) {
            // 獲取緩沖區(qū)位置,即讀取長度
            int readSize = byteBuffer.position();
            // 將讀取位置置0,并將讀取位置標為廢棄
            byteBuffer.rewind();
            // 讀取內容
            byte[] readByte = new byte[readSize];
            byteBuffer.get(readByte);
            // 清除緩存區(qū)
            byteBuffer.clear();
            // 讀取內容是否包含一整行
            boolean hasLF = false;
            int startNum = 0;
            for (int i = 0; i < readSize; i++) {
                if (readByte[i] == ASCII_LF) {
                    hasLF = true;
                    int tempNum = temp.length;
                    int lineNum = i - startNum;
                    // 數(shù)組大小已經去掉換行符
                    lineByte = new byte[tempNum + lineNum];
                    System.arraycopy(temp, 0, lineByte, 0, tempNum);
                    temp = new byte[0];
                    System.arraycopy(readByte, startNum, lineByte, tempNum, lineNum);
                    String line = new String(lineByte, 0, lineByte.length, CHARSET_NAME);
                    content.add(line);
                    // 過濾回車符和換行符
                    if (i + 1 < readSize && readByte[i + 1] == ASCII_CR) {
                        startNum = i + 2;
                    } else {
                        startNum = i + 1;
                    }
                }
            }
            if (hasLF) {
                temp = new byte[readByte.length - startNum];
                System.arraycopy(readByte, startNum, temp, 0, temp.length);
            } else {
                // 單次讀取的內容不足一行的情況
                byte[] toTemp = new byte[temp.length + readByte.length];
                System.arraycopy(temp, 0, toTemp, 0, temp.length);
                System.arraycopy(readByte, 0, toTemp, temp.length, readByte.length);
                temp = toTemp;
            }
        }
        // 最后一行
        if (temp.length > 0) {
            String lastLine = new String(temp, 0, temp.length, CHARSET_NAME);
            content.add(lastLine);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
//        content.forEach(System.out::println);
    System.out.println(content.size());
}

5. 使用cmmons-io依賴提供的FileUtils工具類讀取文件

添加依賴:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>
public static void fileOfCommonsIO() {
        String fileName = "D:\\test.txt";
        final String CHARSET_NAME = "UTF-8";
        List<String> content = new ArrayList<>(0);
        try {
            content = FileUtils.readLines(new File(fileName), CHARSET_NAME);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        content.forEach(System.out::println);
        System.out.println(content.size());
    }

6. 使用cmmons-io依賴提供的IOtils工具類讀取文件

添加依賴:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>
public static void ioOfCommonsIO() {
        String fileName = "D:\\test.txt";
        final String CHARSET_NAME = "UTF-8";
        List<String> content = new ArrayList<>(0);
        try {
            content = IOUtils.readLines(new FileInputStream(fileName), CHARSET_NAME);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        content.forEach(System.out::println);
        System.out.println(content.size());
    }

7. 使用hutool依賴提供的FileUtil工具類讀取文件

添加依賴:

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-core</artifactId>
    <version>5.8.10</version>
</dependency>
或者:
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.10</version>
</dependency>
public static void fileOfHutool() {
        String fileName = "D:\\test.txt";
        final String CHARSET_NAME = "UTF-8";
        List<String> content = FileUtil.readLines(fileName, CHARSET_NAME);
//        content.forEach(System.out::println);
        System.out.println(content.size());
    }

8. 使用hutool依賴提供的IoUtil工具類讀取文件

添加依賴:

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-core</artifactId>
    <version>5.8.10</version>
</dependency>
或者:
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.10</version>
</dependency>
public static void ioOfHutool() {
        String fileName = "D:\\test.txt";
        final String CHARSET_NAME = "UTF-8";
        List<String> content = new ArrayList<>();
        try {
            IoUtil.readLines(new FileInputStream(fileName), CharsetUtil.charset(CHARSET_NAME), content);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        content.forEach(System.out::println);
        System.out.println(content.size());
    }

9. 測試耗時

  測試文件:30000行、21.8 MB

public static void main(String[] args) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start("stream");
    stream();
    stopWatch.stop();
    stopWatch.start("nioOfJDK7");
    nioOfJDK7();
    stopWatch.stop();
    stopWatch.start("streamOfJDK7");
    streamOfJDK7();
    stopWatch.stop();
    stopWatch.start("nioOfJDK4");
    nioOfJDK4();
    stopWatch.stop();
    stopWatch.start("fileOfCommonsIO");
    fileOfCommonsIO();
    stopWatch.stop();
    stopWatch.start("ioOfCommonsIO");
    ioOfCommonsIO();
    stopWatch.stop();
    stopWatch.start("fileOfHutool");
    fileOfHutool();
    stopWatch.stop();
    stopWatch.start("ioOfHutool");
    ioOfHutool();
    stopWatch.stop();
    for (StopWatch.TaskInfo taskInfo : stopWatch.getTaskInfo()) {
        System.out.println(taskInfo.getTaskName() + " -> " + taskInfo.getTimeMillis() + " ms");
    }
//    System.out.println(stopWatch.prettyPrint());
}

測試3次耗時統(tǒng)計(單位:ms):

測試序號streamnioOfJDK7streamOfJDK7nioOfJDK4fileOfCommonsIOioOfCommonsIOfileOfHutoolioOfHutool
1110113852141096417860
298126772361357016959
3106122902241306816562

  從測試結果來看,Hutool提供的IoUtil、commons-io提供的IoUtil以及JDK1.7提供的NIO基于流方式耗時更優(yōu),但測試還應參考內存占用情況,具體可自行測試。

總結

到此這篇關于Java讀取文件的幾種方式的文章就介紹到這了,更多相關Java讀取文件方式內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • java打印當前方法名示例分享

    java打印當前方法名示例分享

    在C與C++中可以打印當前函數(shù)名,但在Java沒有此說法,一切即對象,得從某個對象中去獲取,下面介紹兩種方式打印當前方法名
    2014-02-02
  • 構建多模塊的Spring Boot項目步驟全紀錄

    構建多模塊的Spring Boot項目步驟全紀錄

    這篇文章主要給大家介紹了關于如何構建多模塊的Spring Boot項目的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用SpringBoot具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧
    2019-05-05
  • 詳解mybatis-plus使用@EnumValue注解的方式對枚舉類型的處理

    詳解mybatis-plus使用@EnumValue注解的方式對枚舉類型的處理

    這篇文章主要介紹了詳解mybatis-plus使用@EnumValue注解的方式對枚舉類型的處理,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-12-12
  • Java畢業(yè)設計實戰(zhàn)之線上水果超市商城的實現(xiàn)

    Java畢業(yè)設計實戰(zhàn)之線上水果超市商城的實現(xiàn)

    這是一個使用了java+SSM+springboot+redis開發(fā)的網上水果超市商城,是一個畢業(yè)設計的實戰(zhàn)練習,具有水果超市商城該有的所有功能,感興趣的朋友快來看看吧
    2022-01-01
  • Servlet實現(xiàn)文件的上傳與下載

    Servlet實現(xiàn)文件的上傳與下載

    這篇文章主要為大家詳細介紹了Servlet實現(xiàn)文件的上傳與下載,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-03-03
  • Struts2開發(fā)環(huán)境搭建 附簡單登錄功能實例

    Struts2開發(fā)環(huán)境搭建 附簡單登錄功能實例

    這篇文章主要介紹了Struts2開發(fā)環(huán)境搭建,為大家分享一個簡單登錄功能實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-11-11
  • SpringBoot使用@Cacheable注解實現(xiàn)緩存功能流程詳解

    SpringBoot使用@Cacheable注解實現(xiàn)緩存功能流程詳解

    最近一直再學Spring Boot,在學習的過程中也有過很多疑問。為了解答自己的疑惑,也在網上查了一些資料,以下是對@Cacheable注解的一些理解
    2023-01-01
  • Maven中的<scope>元素使用解讀

    Maven中的<scope>元素使用解讀

    Maven的<scope>控制依賴范圍和生命周期,影響編譯、測試、運行階段的可見性及打包,常見類型包括compile、provided、runtime等,用于管理依賴傳遞與沖突解決,如使用exclusions排除沖突
    2025-09-09
  • Java圖形界面框架AWT布局管理器詳解

    Java圖形界面框架AWT布局管理器詳解

    這篇文章主要介紹了Java圖形界面框架AWT布局管理器,AWT是最早的圖形用戶界面框架之一,它為開發(fā)人員提供了一些基本的組件和工具,用于構建窗口、按鈕、文本框、標簽等圖形界面元素,需要的朋友可以參考下
    2025-04-04
  • Spring深入了解常用配置應用

    Spring深入了解常用配置應用

    這篇文章主要給大家介紹了關于Spring的常用配置,文中通過示例代碼介紹的非常詳細,對大家學習或者使用springboot具有一定的參考學習價值,需要的朋友可以參考下
    2022-07-07

最新評論

大关县| 陈巴尔虎旗| 宁化县| 木兰县| 巴楚县| 霍林郭勒市| 林甸县| 钟山县| 犍为县| 禹州市| 深州市| 思茅市| 丰都县| 黄梅县| 绵阳市| 滦平县| 成武县| 浦县| 开封市| 达孜县| 达孜县| 彩票| 河西区| 西青区| 扎兰屯市| 诸城市| 湘潭市| 永寿县| 麻江县| 梅州市| 牡丹江市| 梅河口市| 若尔盖县| 青海省| 澜沧| 灵川县| 嵩明县| 无棣县| 河北省| 绿春县| 襄垣县|