百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

在Java里如何读取文件(java实现读取文件)

itomcoil 2025-07-06 12:57 2 浏览

1.概述

在这篇文章里, 我们将探索不同的方式从文件中读取数据。

首先, 学习通过标准的的Java类,从classpathURL或者Jar中加载文件。

然后,学习通用BufferedReader, Scanner, StreamTokenizer, DataInputStream, SequenceInputStream, FileChannel读取文件内容。也会讨论如何读取UTF-8编码的文件。

最后,学习Java7和Java8中新的加载和读取文件的技术。

2.准备

2.1 输入文件

这篇文章的很多示例,从名为fileTest.txt的文件读取文本内容,文件包含

Hello,World!

有少量示例, 我们会读取不同的文件, 示例中会有说明。

2.2 辅助方法

很多示例都会用到共用的方法readFromInputStream, 该方法将InputStream转化String

    private String readFromInputStream(InputStream inputStream)
            throws IOException {
        StringBuilder resultStringBuilder = new StringBuilder();
        try (BufferedReader br
                     = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;
            while ((line = br.readLine()) != null) {
                resultStringBuilder.append(line).append("\n");
            }
        }
        return resultStringBuilder.toString();
    }

3.从Classpath读取文件

3.1 使用标准Java

src/main/resources读取文件fileTest.txt

    @Test
    public void test() throws IOException {
        String expectedData = "Hello,World!";
        Class<ReadFileTest> clazz = ReadFileTest.class;
        InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
        String data = readFromInputStream(inputStream);

        Assert.assertThat(data, containsString(expectedData));
    }

在上面的代码中,我们通过当前类的getResourceAsStream方法加载文件,入参是绝对路径。

ClassLoader中相同的方法也可以使用。

ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("fileTest.txt");
String data = readFromInputStream(inputStream);

这两种方法的主要区别是, 当前类的ClassLoadergetResourceAsStream方法,入参路径是从classpath开始。

而类实例的入参是相对于包路径,但路径开始使用'/'符号, 也是绝对路径。

特别要注意的是, 文件打开读取完数据后, 始终需要关闭

inputStream.close();

3.2 使用commons-io库

另一个比较常用的方法是使用commons-io包里的FileUtils.readFileToString方法。

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.4</version>
        </dependency>
    @Test
    public void useCommonIO() throws IOException {
        String expectedData = "Hello,World!";

        ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(classLoader.getResource("fileTest.txt").getFile());
        String data = FileUtils.readFileToString(file, "UTF-8");

        assertEquals(expectedData, data.trim());
    }

该方法入参是File对象。这个工具类的优点是不用编码InputStream实例的相关代码。
这个库还提供了IOUtils类。

    @Test
    public void useCommonIO2() throws IOException {
        String expectedData = "Hello,World!";

        FileInputStream fis = new FileInputStream("src/test/resources/fileTest.txt");
        String data = IOUtils.toString(fis, "UTF-8");

        assertEquals(expectedData, data.trim());
    }

4.BufferedReader

@Test
public void bufferedReader() throws IOException {
    String expected_value = "Hello,World!";
    String file ="src/test/resources/fileTest.txt";

    BufferedReader reader = new BufferedReader(new FileReader(file));
    String currentLine = reader.readLine();
    reader.close();

    assertEquals(expected_value, currentLine);
}

当读取结束的时候, reader.readLine()会返回null

5.Java NIO

NIO是在JDK7中添加。

5.1读取小文件

首先看一下关于Files.readAllLines的示例

    @Test
    public void readSmallFile()  throws IOException {
        String expected_value = "Hello,World!";

        Path path = Paths.get("src/test/resources/fileTest.txt");

        String read = Files.readAllLines(path).get(0);
        assertEquals(expected_value, read);
    }

入参Path对象,Path可以认为是java.io.File的升级版本,提供一些额外的功能。

如果读取的是二进制文件,可以使用Files.readAllBytes()方法

5.2读取大文件

如果想要读取大文件, 我们可以使用Files类和BufferedReader类。

    @Test
    public void readLargeFile() throws IOException {
        String expected_value = "Hello,World!";

        Path path = Paths.get("src/test/resources/fileTest.txt");

        BufferedReader reader = Files.newBufferedReader(path);
        String line = reader.readLine();
        assertEquals(expected_value, line);
    }

5.3Files.lines

在JDK8中,Files类增加了lines方法,这个方法将返回Stream<String>。跟文件操作一样,Stream需要显式调用的close()。Files API提供了很多简单读取文件的方法。

6.Scanner

下面我们将使用Scanner读取文件,使用逗号(,)作为定界符(delimiter)。

@Test
public void whenReadWithScanner_thenCorrect()
        throws IOException {
    String file = "src/test/resources/fileTest.txt";
    Scanner scanner = new Scanner(new File(file));
    scanner.useDelimiter(",");

    assertTrue(scanner.hasNext());
    assertEquals("Hello", scanner.next());
    assertEquals("World!", scanner.next());

    scanner.close();
}

Scanner默认的定界符是空格。它适用于从控制台读取输入或者内容有固定定界符的内容时。

7.StreamTokenizer

tokenizer会指出下一个token的类型,String或Number。

tokenizer.nval - 如果类型为Number时,读取该字段

tokenizer.sval - 如果类型为String时,读取该字段

@Test
public void readWithTokenize()
        throws IOException {
    String file = "src/test/resources/fileTestTokenizer.txt";
    FileReader reader = new FileReader(file);
    StreamTokenizer tokenizer = new StreamTokenizer(reader);

    //  1
    tokenizer.nextToken();
    assertEquals(StreamTokenizer.TT_WORD, tokenizer.ttype);
    assertEquals("Hello", tokenizer.sval);

    //  2
    tokenizer.nextToken();
    assertEquals(StreamTokenizer.TT_NUMBER, tokenizer.ttype);
    assertEquals(1, tokenizer.nval, 0.0000001);

    //  3
    tokenizer.nextToken();
    assertEquals(StreamTokenizer.TT_EOF, tokenizer.ttype);
    reader.close();
}

8.DataInputStream

如果要读取二进制文件或者原生数据,可以使用DataInputStream

@Test
public void whenReadWithDataInputStream() throws IOException {
    String expectedValue = "Hello,World!";
    String file ="src/test/resources/fileTest.txt";
    String result = null;

    DataInputStream reader = new DataInputStream(new FileInputStream(file));
    int nBytesToRead = reader.available();
    if(nBytesToRead > 0) {
        byte[] bytes = new byte[nBytesToRead];
        reader.read(bytes);
        result = new String(bytes);
    }

    assertEquals(expectedValue, result);
}

9.FileChannel

如果读取的是一个大文件,FileChannel速度会超过standard IO。

@Test
public void whenReadWithFileChannel()
        throws IOException {
    String expected_value = "Hello,World!";
    String file = "src/test/resources/fileTest.txt";
    RandomAccessFile reader = new RandomAccessFile(file, "r");
    FileChannel channel = reader.getChannel();

    int bufferSize = 1024;
    if (bufferSize > channel.size()) {
        bufferSize = (int) channel.size();
    }
    ByteBuffer buff = ByteBuffer.allocate(bufferSize);
    channel.read(buff);
    buff.flip();

    assertEquals(expected_value, new String(buff.array()));
    channel.close();
    reader.close();
}

10.读取utf-8编码的文件

@Test
public void whenReadUTFEncodedFile()
        throws IOException {
    String expected_value = "你好,世界!";
    String file = "src/test/resources/fileTestUtf8.txt";
    BufferedReader reader = new BufferedReader
            (new InputStreamReader(new FileInputStream(file), "UTF-8"));
    String currentLine = reader.readLine();
    reader.close();

    assertEquals(expected_value, currentLine);
}

11.从URL读取数据

@Test
public void readFromURL() throws IOException {
    URL urlObject = new URL("https://www.baidu.com");
    URLConnection urlConnection = urlObject.openConnection();
    InputStream inputStream = urlConnection.getInputStream();
    String data = readFromInputStream(inputStream);
}

12.从jar包中读取文件

我们的目标是读取junit-4.12.jar包中的LICENSE-junit.txt文件。clazz只需要这个Jar中的类就行。

@Test
public void readFromJar() throws IOException {
    String expectedData = "Eclipse Public License";

    Class clazz = Test.class;
    InputStream inputStream = clazz.getResourceAsStream("/LICENSE-junit.txt");
    String data = readFromInputStream(inputStream);

    Assert.assertThat(data, containsString(expectedData));
}

相关推荐

zabbix企业微信告警(zabbix5.0企业微信告警详细)

zabbix企业微信告警的前提是用户有企业微信且创建了一个能够发送消息的应用,具体怎么创建可以协同用户侧企业微信的管理员。第一步:企业微信准备我们需要的内容包括企业ID,应用的AgentId和应用的S...

基于centos7部署saltstack服务器管理自动化运维平台

概述SaltStack是一个服务器基础架构集中化管理平台,具备配置管理、远程执行、监控等功能,基于Python语言实现,结合轻量级消息队列(ZeroMQ)与Python第三方模块(Pyzmq、PyCr...

功能实用,效率提升,Python开发的自动化运维工具

想要高效的完成日常运维工作,不论是代码部署、应用管理还是资产信息录入,都需要一个自动化运维平台。今天我们分享一个开源项目,它可以帮助运维人员完成日常工作,提高效率,降低成本,它就是:OpsManage...

centos定时任务之python脚本(centos7执行python脚本)

一、crontab的安装默认情况下,CentOS7中已经安装有crontab,如果没有安装,可以通过yum进行安装。yuminstallcrontabs二、crontab的定时语法说明*代表取...

Fedora 41 终于要和 Python 2.7 说再见了

红帽工程师MiroHroncok提交了一份变更提案,建议在Fedora41中退役Python2.7,并放弃仍然依赖Python2的软件包。Python2已于2020年1...

软件测试|使用docker搞定 Python环境搭建

前言当我们在公司的电脑上搭建了一套我们需要的Python环境,比如我们的版本是3.8的Python,那我可能有一天换了一台电脑之后,我整套环境就需要全部重新搭建,不只是Python,我们一系列的第三方...

环境配置篇:Centos如何安装Python解释器

有小伙伴时常会使用Python进行编程,那么如何配置centos中的Python环境呢?1)先安装依赖yuminstallgccgcc-c++sqlite-devel在root用户下操作:1...

(三)Centos7.6安装MySql(centos8.3安装docker)

借鉴文章:centos7+django+python3+mysql+阿里云部署项目全流程。这里我只借鉴安装MySql这一部分。链接:https://blog.csdn.net/a394268045/a...

Centos7.9 如何安装最新版本的Docker

在CentOS7.9系统中安装最新版本的Docker,需遵循以下步骤,并注意依赖项的兼容性问题:1.卸载旧版本Docker(如已安装)若系统中存在旧版Docker,需先卸载以避免冲突:sudoy...

Linux 磁盘空间不够用?5 招快速清理文件,释放 10GB 空间不是梦!

刚收到服务器警告:磁盘空间不足90%!装软件提示Nospaceleftondevice!连日志都写不进去,系统卡到崩溃?别慌!今天教你5个超实用的磁盘清理大招,从临时文件到无用软件一键搞定...

Playwright软件测试框架学习笔记(playwright 官网)

本文为霍格沃兹测试开发学社学员学习笔记,人工智能测试开发进阶学习文末加群。一,Playwright简介Web自动化测试框架。跨平台多语言支持。支持Chromium、Firefox、WebKit...

为SpringDataJpa集成QueryObject模式

1.概览单表查询在业务开发中占比最大,是所有CRUDBoy的入门必备,所有人在JavaBean和SQL之间乐此不疲。而在我看来,该部分是最枯燥、最没有技术含量的“伪技能”。1.1.背景...

金字塔测试原理:写好单元测试的8个小技巧,一文总结

想必金字塔测试原理大家已经很熟悉了,近年来的测试驱动开放在各个公司开始盛行,测试代码先写的倡议被反复提及。鉴于此,许多中大型软件公司对单元测试的要求也逐渐提高。那么,编写单元测试有哪些小技巧可以借鉴和...

测试工程师通常用哪个单元测试库来测试Java程序?

测试工程师在测试Java程序时通常使用各种不同的单元测试库,具体选择取决于项目的需求和团队的偏好。我们先来看一些常用的Java单元测试库,以及它们的一些特点:  1.JUnit:  ·描述:JUn...

JAVA程序员自救之路——SpringAI评估

背景我们用SpringAI做了大模型的调用,RAG的实现。但是我们做的东西是否能满足我们业务的要求呢。比如我们问了一个复杂的问题,大模型能否快速准确的回答出来?是否会出现幻觉?这就需要我们构建一个完善...