Java –从资源文件夹中读取文件

在本教程中,我们将向您展示如何在运行时和单元测试环境中从resources文件夹或类路径读取文件。 尝试将文件放入src/main/resources文件夹,并使用以下代码段读取文件:

1. getResource

File file = new File(
		getClass().getClassLoader().getResource("database.properties").getFile()
	);

2. getResourceAsStream

InputStream inputStream = getClass()
			.getClassLoader().getResourceAsStream("database.properties");

注意
您可能会对静态方法中的getResourceAsStream感兴趣

1.项目目录

查看Maven项目结构。

项目目录

2.从资源文件夹中读取文件

src/main/resources/database.properties
datasource.url=jdbc:mysql://localhost/mkyong?useSSL=false
datasource.username=root
datasource.password=password
datasource.driver-class-name=com.mysql.jdbc.Driver

读取database.properties文件并打印出内容。

Application.java
package com.mkyong;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;

public class Application {

    public static void main(String[] args) throws IOException {

        Application main = new Application();
        File file = main.getFileFromResources("database.properties");

        printFile(file);
    }

    // get file from classpath, resources folder
    private File getFileFromResources(String fileName) {

        ClassLoader classLoader = getClass().getClassLoader();

        URL resource = classLoader.getResource(fileName);
        if (resource == null) {
            throw new IllegalArgumentException("file is not found!");
        } else {
            return new File(resource.getFile());
        }

    }

    private static void printFile(File file) throws IOException {

        if (file == null) return;

        try (FileReader reader = new FileReader(file);
             BufferedReader br = new BufferedReader(reader)) {

            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }
    }

}

输出量

datasource.url=jdbc:mysql://localhost/mkyong?useSSL=false
datasource.username=root
datasource.password=password
datasource.driver-class-name=com.mysql.jdbc.Driver

3.单元测试

src/test/resources/xml/data.xml
<test>
    <case id='1'>
        <param>100</param>
        <expected>mkyong</expected>
    </case>
    <case id='2'>
        <param>99</param>
        <expected>mkyong</expected>
    </case>
</test>

读取data.xml并打印出内容。

ApplicationTest.java
package com.mkyong;

import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class ApplicationTest {

    @DisplayName("Test loading XML")
    @Test
    void loadXMLTest() {

        ClassLoader classLoader = getClass().getClassLoader();

        try (InputStream inputStream = classLoader.getResourceAsStream("xml/data.xml")) {

            String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
            System.out.println(result);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

输出量

<test>
    <case id='1'>
        <param>100</param>
        <expected>mkyong</expected>
    </case>
    <case id='2'>
        <param>99</param>
        <expected>mkyong</expected>
    </case>
</test>
pom.xml
<dependencies>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.4.2</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

下载源代码

下载– java-get-file-from-resources.zip (6KB)

参考文献

翻译自: https://mkyong.com/java/java-read-a-file-from-resources-folder/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值