Java读取文件方式

news2024/10/8 14:19:03

IO流读取

文本内容

 

按行读取文件内容

指定编码格式(推荐)

 public static void main(String[] args) throws UnsupportedEncodingException {
        read("D:\\test.txt");

    }

    public static void read(String path) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(path), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

 注意,如果控制台输出为乱码,需要度idea进行配置,依次选择file-Setting-editor-File Encoding

 不指定编码格式

 public static void main(String[] args) throws IOException {
        read("D:\\test.txt");

    }

    public static void read(String path) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(path));
        String line;
        while ((line = reader.readLine()) != null)
        {
            System.out.println(line);
        }
        reader.close();
    }

可能出现乱码。

按字符读取文件内容

 public static void read(String path) throws IOException {
        Reader reader = new InputStreamReader(new FileInputStream(path));
        int tempchar;
        while ((tempchar = reader.read()) != -1) {
            System.out.print((char) tempchar);
        }
        reader.close();
    }

按字节读取文件内容

常用于读取图片,声音,影像等

单字节读取

 public static void read(String path) throws IOException {
        FileInputStream reader = new FileInputStream(path);
        int tempchar;
        while ((tempchar = reader.read()) != -1) {
            System.out.print((char) tempchar);
        }
        reader.close();
    }

多字节读取

 public static void read(String path) throws IOException {
        FileInputStream reader = new FileInputStream(path);
        byte[] tempByte = new byte[1024];
        int len = 0 ;
        while((len = reader.read(tempByte))!= -1){
            for (int i = 0; i <len; i++) {
                System.out.print((char)tempByte[i]);
            }
        }
        reader.close();
    }

Scanner

第一种方式是Scanner,从JDK1.5开始提供的API,特点是可以按行读取、按分割符去读取文件数据,既可以读取String类型,也可以读取Int类型、Long类型等基础数据类型的数据。

  public static void read(String path) throws IOException {
        try (Scanner sc = new Scanner(new FileReader(path))) {
            while (sc.hasNextLine()) {  //按行读取字符串
                String line = sc.nextLine();
                System.out.println(line);
            }
        }
    }

JDK1.7提供的NIO读取文件

小文件

 public static void read(String path) throws IOException {
        final String CHARSET_NAME = "UTF-8";

        List<String> content = new ArrayList<>(0);

        try {
            content = Files.readAllLines(Paths.get(path), Charset.forName(CHARSET_NAME));
        } catch (Exception e) {
            e.printStackTrace();
        }

       content.forEach(System.out::println);

    }

大文件

 public static void read(String path) throws IOException {
        final String CHARSET_NAME = "UTF-8";

        List<String> content = new ArrayList<>(0);


        try (BufferedReader br = Files.newBufferedReader(Paths.get(path), Charset.forName(CHARSET_NAME))) {
            String line;
            while ((line = br.readLine()) != null) {
                content.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

       content.forEach(System.out::println);

    }

JDK1.4提供的NIO读取文件(适用于超大文件)

public static void read(String path) throws IOException {
        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(path, "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);

    }

 JDK1.7 Files.readAllBytes

 public static void read(String path) throws IOException {

        byte[] bytes = Files.readAllBytes(Paths.get(path));

        String content = new String(bytes, StandardCharsets.UTF_8);
        System.out.println(content);
    }

 JDK1.8 Stream流

可能会出现内存溢出问题 java.lang.OutOfMemoryError

Files.lines

public static void read(String path) throws IOException {
        // 读取文件内容到Stream流中,按行读取
        Stream<String> lines = Files.lines(Paths.get(path));

        // 随机行顺序进行数据处理
        lines.forEach(System.out::println);
    }

forEach获取Stream流中的行数据不能保证顺序,但速度快。如果你想按顺序去处理文件中的行数据,可以使用forEachOrdered,但处理效率会下降。


lines.forEachOrdered(System.out::println);

或者利用CPU多和的能力,进行数据的并行处理parallel(),适合比较大的文件


lines.parallel().forEachOrdered(System.out::println);

Files.readAllLines

public static void read(String path) throws IOException {
    // 读取文件内容到Stream流中,按行读取
    List<String> lines =  Files.readAllLines(Paths.get(path),
            StandardCharsets.UTF_8);

    // 随机行顺序进行数据处理
    lines.forEach(System.out::println);
}

 JDK 11 Files.readString()

文件不能超过2G,同时要注意你的服务器及JVM内存。这种方法适合快速读取小文本文件。

     System.out.println(Files.readString(Paths.get(path))); 

依赖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 read(String path) throws IOException {
        final String CHARSET_NAME = "UTF-8";


        List<String> content = new ArrayList<>();

        try {
            IoUtil.readLines(new FileInputStream(path), CharsetUtil.charset(CHARSET_NAME), content);
        } catch (Exception e) {
            e.printStackTrace();
        }
       content.forEach(System.out::println);

    }

 FileUtil工具类

public static void fileOfHutool() {
    
        final String CHARSET_NAME = "UTF-8";

        List<String> content = FileUtil.readLines(path, CHARSET_NAME);

        content.forEach(System.out::println);
      
    }

依赖cmmons-io

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

FileUtils工具类

    public static void read(String path) throws IOException {
        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);

    }

IOUtils工具类

public static void read(String path) throws IOException {
        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);

    }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/443230.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Spring Security 01 整体架构

目录 认证 AuthenticationManager ProviderManager AuthenticationProvider Authentication SecurityContextHolder 授权 AccessDecisionManager AccessDecisionVoter RoleVoter AuthenticatedVoter Custom Voters ConfigAttribute 在SpringSecurity的架构中&…

Linux如何使用宝塔面板搭建网站和内网穿透实现公网访问

文章目录 前言1. 环境安装2. 安装cpolar内网穿透3. 内网穿透4. 固定http地址5. 配置二级子域名6. 创建一个测试页面 转载自远程内网穿透的文章&#xff1a;Linux使用宝塔面板搭建网站&#xff0c;并内网穿透实现公网访问 前言 宝塔面板作为简单好用的服务器运维管理面板&#…

Flink从入门到精通之-06Flink 中的时间和窗口

Flink从入门到精通之-06Flink 中的时间和窗口 我们已经了解了基本 API 的用法&#xff0c;熟悉了 DataStream 进行简单转换、聚合的一些操作。除此之外&#xff0c;Flink 还提供了丰富的转换算子&#xff0c;可以用于更加复杂的处理场景。 在流数据处理应用中&#xff0c;一个…

NM储存卡数据丢失怎么办?四招数据恢复宝典

NM卡像其他类型的存储设备一样&#xff0c;也有可能因为各种原因导致数据丢失&#xff0c;比如误删除、格式化、病毒感染等。因此&#xff0c;在使用NM卡时&#xff0c;仍需注意数据备份和安全性&#xff0c;以避免面临重要数据丢失风险。如果不幸发生了数据丢失&#xff0c;应…

python中unexpected indent报错的解决办法

python中unexpected indent报错的解决办法 在我们初步学习pyton的时候&#xff0c;由于对python语言的学习掌握不充分&#xff0c;则会导致所编写的代码&#xff0c;运行时候报错。比如&#xff0c;容易报错的unexpected indent问题&#xff0c;下面举例说明问题。 1.举例&am…

Linux虚拟机中安装jdk的两种方法:

方法一&#xff1a;手动安装 1. 使用FinalShell自带的上传工具将jdk的二进制发布包上传到Linux 上传位置如图&#xff08;底栏可以在图中的向下箭头位置自行打开与关闭&#xff09;&#xff1a; 注&#xff1a;默认上传地址为图片左侧的工作地址 2. 解压安装包&#xff0c;…

在vue2中用vue-echarts和v-charts绘制百度地图定制散点图

一、在vue-echarts中定制百度地图 效果 准备 安装依赖 echarts vue-echarts npm i echarts vue-echarts 在main.js中引入 import ECharts from “echarts” import VueECharts from “vue-echarts” Vue.prototype.$echarts ECharts Vue.component(“v-chart”, VueECharts…

SAS学习第4章:t检验

前话&#xff1a;分析试验数据的差异&#xff0c;一般都会假设样本值之间或者样本与标准值之间无差异&#xff0c;根据不同方法计算得出的t值、q值、F值等等&#xff0c;均表示两者之间的差异程度&#xff0c;值越大&#xff0c;两者差异越大&#xff0c;该假设越不成立&#x…

全网最全的AI绘画提示词网站,看这一篇就够了!

要说2023年什么最火&#xff0c;绝对是以ChatGPT为代表的AI工具了&#xff0c;特别是AI绘画&#xff0c;而用好AI的关键&#xff0c;就是要学会使用关键词&#xff0c;也叫提示词&#xff0c;提示词是AI绘画的核心&#xff0c;本次就给大家分享几个AI绘画关键词网站&#xff0c…

大型Android项目架构:基于组件化+模块化+Kotlin+协程+Flow+Retrofit+Jetpack+MVVM架构实现WanAndroid客户端

前言&#xff1a;苟有恒&#xff0c;何必三更眠五更起&#xff1b;最无益&#xff0c;莫过一日曝十日寒。 前言 之前一直想写个 WanAndroid 项目来巩固自己对 KotlinJetpack协程 等知识的学习&#xff0c;但是一直没有时间。这里重新行动起来&#xff0c;从项目搭建到完成前前…

奇异值分解SVD

概念 奇异值分解&#xff08;singular value decomposition&#xff09;是线性代数中一种重要的矩阵分解。奇异值分解在某些方面与对称矩阵或厄密矩阵基于特征向量的对角化类似。然而这两种矩阵分解尽管有其相关性&#xff0c;但还是有明显的不同。对称矩阵特征向量分解的基础…

数据分析师 ---- SQL强化(1)

文章目录 数据分析师 ---- SQL强化(1)写在前面题目第一步&#xff1a;表连接以及表拼接第二步&#xff1a;新建列以及填充值总结 数据分析师 ---- SQL强化(1) 写在前面 最近在找工作中发现&#xff0c;数据分析师的笔试多数会涉及SQL&#xff0c;但是笔试中SQL的难度和我们在学…

车载软件架构——闲聊几句AUTOSAR BSW(一)

我是穿拖鞋的汉子,魔都中坚持长期主义的工程师。 老规矩,分享一段喜欢的文字,避免自己成为高知识低文化的工程师: 人生是用来体验的,不是用来演绎完美的。我慢慢能接受自己身上那些灰暗的部分,原谅自己的迟钝和平庸,允许自己出错,允许自己偶尔断电,带着缺憾拼命绽放,…

Node【初识Node】

文章目录 &#x1f31f;前言&#x1f31f;Node.js&#x1f31f;特性&#xff1a;&#x1f31f;1. 单线程&#x1f31f;2.异步IO&#x1f31f;前端中的异步&#x1f31f;Node中的异步 &#x1f31f;3.跨平台&#x1f31f;4.运行速度快 &#x1f31f; 劣势&#xff1a;&#x1f3…

4/20~4/21两日总结

网络编程 socket通信 socket被翻译为套接字&#xff0c;通过socket这种约定&#xff0c;一台计算机可以接收其他计算机的数据&#xff0c;也可以向其他计算机发送数据 如何实现呢 ServerSocket类能创建Socket的服务端&#xff0c;Socket能创建Socket的客户端 ServerSocket中…

如何运用数字孪生可视化技术实现三维可视化智慧园区

随着城市化的进程和信息化的发展&#xff0c;越来越多的城市拥有了智慧园区这一新的城市形态&#xff0c;通过“互联网”和物联网技术&#xff0c;实现了各种功能部门之间的信息共享与协同&#xff0c;提高了园区服务的质量和效率。然而&#xff0c;如何更好地实现园区管理和运…

LeetCode - 168. Excel表列名称

168. Excel表列名称 给你一个整数 columnNumber &#xff0c;返回它在 Excel 表中相对应的列名称。例如&#xff1a; A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... 二进制与十进制之间的转换 在做这题之前&#xff0c;先复习一下二进制与十进…

JUC并发编程之读写锁原理

1.图解流程 读写锁用的是同一个 Sycn 同步器&#xff0c;因此等待队列、state等也是同一个 t1 w.lock &#xff0c; t2 r.lock t1 成功上锁&#xff0c;流程与 ReentrantLock 加锁相比没有特殊之处&#xff0c;不同的是写锁状态占了 state 的低 16 位&#xff0c;而读锁使用…

多线程并发编程-线程篇

线程基础 什么是线程&#xff1f; 系统中的一个程序就是一个进程&#xff0c;每个进程中的最基本的执行单位&#xff0c;执行路径就是线程&#xff0c;线程是轻量化的进程。 什么是纤程&#xff1f; 绿色线程&#xff0c;由用户自己进行管理的而不是系统进行管理的&#xf…

【教程类】IDEA 打包 jar 包

最近有点累&#xff0c;写点简单的图文教程的东西来缓解一下 一、你需要知道的基础概念 了解了基础概念之后&#xff0c;可以让我们学习的更快更好哦 ~~ 1. jar JAR&#xff08;Java Archive&#xff09;是Java中一种常用的归档文件格式&#xff0c;也可以被视为一种压缩文…