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) {
            // 获取缓冲区位置,即读取长度
            int readSize = byteBuffer.position();

            // 将读取位置置0,并将读取位置标为废弃
            byteBuffer.rewind();

            // 读取内容
            byte[] readByte = new byte[readSize];
            byteBuffer.get(readByte);

            // 清除缓存区
            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;

                    // 数组大小已经去掉换行符
                    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次耗时统计(单位:ms):

测试序号 stream nioOfJDK7 streamOfJDK7 nioOfJDK4 fileOfCommonsIO ioOfCommonsIO fileOfHutool ioOfHutool
1 110 113 85 214 109 64 178 60
2 98 126 77 236 135 70 169 59
3 106 122 90 224 130 68 165 62

  从测试结果来看,Hutool提供的IoUtil、commons-io提供的IoUtil以及JDK1.7提供的NIO基于流方式耗时更优,但测试还应参考内存占用情况,具体可自行测试。文章来源地址https://www.toymoban.com/news/detail-579872.html

到了这里,关于Java读取文件的几种方式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • Java解压RAR文件的几种方式

    2024年02月16日
    浏览(10)
  • Java如何实现下载文件的几种方式

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/Boy_Martin/article/details/126058565

    2024年02月13日
    浏览(15)
  • Java开发或调用WebService的几种方式

    Java开发或调用WebService的几种方式

    1.服务端开发与发布 编写接口 编写接口的实现类 发布服务 访问已发布的WebService服务 打开浏览器输入http://127.0.0.1:8888/JaxWSTest?wsdl访问,如下面内容 截图内容1 浏览器中输入wsdl文档中的 http://127.0.0.1:8888/JaxWSTest?xsd=1可查看绑定的参数等信息看如下图: 截图内容2 jdk自带生成W

    2024年01月17日
    浏览(15)
  • JAVA开发(通过Apollo注入配置信息的几种方式)

    JAVA开发(通过Apollo注入配置信息的几种方式)

    在springCloud中有一个重要的组件就是配置中心,config:server,用于配置springboot中需要注入的各种配置项。但是现在发现越来越多的企业使用Apollo进行集成。博主在开发中也是使用Apollo进行配置。本文总结Apollo的的使用,集成到springboot,和注入方式等。   Apollo是携程框架部门研

    2024年02月09日
    浏览(9)
  • Unity中常用的几种读取本地文件方式

    使用的命名空间如下 using LitJson; using System.Collections.Generic; using System.IO; using System.Text; using UnityEngine; using UnityEngine.Networking; 1、通过UnityWebRequest获取本地StreamingAssets文件夹中的Json文件 View Code 2、通过UnityWebRequest和StreamReader读取本地StreamingAssets文件夹中的Json文件 View Code  3、通

    2024年02月04日
    浏览(10)
  • 【SpringBoot系列】读取yml文件的几种方式

    【SpringBoot系列】读取yml文件的几种方式

    前言 在Spring Boot开发中,配置文件是非常重要的一部分,而yml文件作为一种常用的配置文件格式,被广泛应用于Spring Boot项目中。Spring Boot提供了多种方式来读取yml文件中的属性值,开发者可以根据具体的需求和场景选择合适的方式。本文将介绍Spring Boot读取yml文件的主要方式

    2024年02月05日
    浏览(10)
  • 前端常用的上传下载文件的几种方式,直接上传、下载文件,读取.xlsx文件数据,导出.xlsx数据

    1.1根据文件流Blob进行下载 1.2根据下载文件链接直接进行下载 html

    2024年02月12日
    浏览(10)
  • 【Spring】1、Spring 框架的基本使用【读取配置文件、IoC、依赖注入的几种方式、FactoryBean】

    【Spring】1、Spring 框架的基本使用【读取配置文件、IoC、依赖注入的几种方式、FactoryBean】

    Spring 框架可以说是 Java 开发中最重要的框架,功能 非常 强大 中文文档:https://springdoc.cn/spring/ 官网:https://spring.io/ Spring makes Java Simple、modern、productive … Spring 框架的几个核心概念: IoC: I nversion o f C ontrol:控制反转 DI: D ependency I njection:依赖注入 AOP: A spect O riented P rogram

    2024年02月09日
    浏览(14)
  • Java判断null的几种方式

    Java判断null的几种方式

    组内code review时,有同学提到字符串判断空值的写法,如下两种, (1)null在后, (2)null在前, 这两种写法,有什么区别? 这两个测试,都可以执行,有种解释是,null放在前面是为了避免少写一个\\\"=\\\",因为\\\"null=\\\"书写会报错,防止笔误写成\\\"=null\\\",不会报错,进而漏掉问题。

    2024年02月13日
    浏览(14)
  • Java实现异步的几种方式

    Java实现异步的几种方式

    普通线程实现异步,但频繁创建、销毁线程比较耗资源,所以一般交给线程池执行 结果: Future异步 和普通线程实现异步区别不大,只是使用Future是要获取执行后的返回值 结果: Spring的@Async异步 使用@Async注解实现异步的前提是需要在启动类上标注@EnableAsync来开启异步配置

    2024年02月04日
    浏览(17)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包