Java案例如何读取资源文件?

wen java案例 15

本文目录导读:

Java案例如何读取资源文件?

  1. 使用 Class.getResourceAsStream()(推荐)
  2. 使用 ClassLoader.getResourceAsStream()
  3. 读取properties配置文件(常见案例)
  4. 读取文本文件内容
  5. 读取JSON文件(使用Jackson)
  6. 读取二进制文件(如图片)
  7. 获取资源文件的URL路径
  8. 资源文件组织结构
  9. 重要提示:

在Java中读取资源文件有多种方式,以下是最常见的几种方法及其适用场景:

使用 Class.getResourceAsStream()(推荐)

// 读取与当前类同包下的资源文件
InputStream inputStream = MyClass.class.getResourceAsStream("config.properties");
// 读取classpath根目录下的资源文件(路径以"/"开头)
InputStream inputStream = MyClass.class.getResourceAsStream("/config.properties");
// 读取子目录下的资源文件
InputStream inputStream = MyClass.class.getResourceAsStream("/resources/config.properties");

使用 ClassLoader.getResourceAsStream()

// 读取classpath根目录下的资源(路径不能以"/"开头)
InputStream inputStream = MyClass.class.getClassLoader()
    .getResourceAsStream("config.properties");
// 读取子目录下的资源
InputStream inputStream = MyClass.class.getClassLoader()
    .getResourceAsStream("resources/config.properties");

读取properties配置文件(常见案例)

import java.io.InputStream;
import java.util.Properties;
public class ConfigReader {
    public static void main(String[] args) {
        Properties properties = new Properties();
        try (InputStream inputStream = ConfigReader.class
                .getClassLoader()
                .getResourceAsStream("app.properties")) {
            if (inputStream != null) {
                properties.load(inputStream);
                // 读取配置值
                String dbUrl = properties.getProperty("database.url");
                String username = properties.getProperty("database.username");
                String password = properties.getProperty("database.password");
                System.out.println("数据库URL: " + dbUrl);
                System.out.println("用户名: " + username);
            } else {
                System.out.println("资源文件未找到");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

读取文本文件内容

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
public class TextFileReader {
    public static String readResourceFile(String filePath) {
        ClassLoader classLoader = TextFileReader.class.getClassLoader();
        try (InputStream inputStream = classLoader.getResourceAsStream(filePath);
             BufferedReader reader = new BufferedReader(
                 new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            return reader.lines().collect(Collectors.joining("\n"));
        } catch (IOException | NullPointerException e) {
            e.printStackTrace();
            return null;
        }
    }
    public static void main(String[] args) {
        String content = readResourceFile("data/example.txt");
        System.out.println(content);
    }
}

读取JSON文件(使用Jackson)

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.InputStream;
public class JsonFileReader {
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        // 读取JSON文件
        try (InputStream inputStream = JsonFileReader.class
                .getClassLoader()
                .getResourceAsStream("user.json")) {
            if (inputStream != null) {
                // 将JSON转换为对象
                User user = mapper.readValue(inputStream, User.class);
                System.out.println(user.getName() + " - " + user.getEmail());
            }
        }
    }
}
class User {
    private String name;
    private String email;
    // getter和setter方法
}

读取二进制文件(如图片)

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
public class ImageResourceReader {
    public static BufferedImage readImage(String imagePath) {
        try (InputStream inputStream = ImageResourceReader.class
                .getClassLoader()
                .getResourceAsStream(imagePath)) {
            if (inputStream != null) {
                return ImageIO.read(inputStream);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

获取资源文件的URL路径

public class ResourcePathExample {
    public static void main(String[] args) {
        // 获取资源的URL
        URL resourceUrl = ResourcePathExample.class
            .getClassLoader()
            .getResource("data/example.txt");
        if (resourceUrl != null) {
            System.out.println("资源URL: " + resourceUrl.getPath());
            // 获取文件对象(仅适用于文件系统中的资源)
            File resourceFile = new File(resourceUrl.getFile());
            System.out.println("文件路径: " + resourceFile.getAbsolutePath());
        }
    }
}

资源文件组织结构

src/
├── main/
│   ├── java/
│   │   └── com/example/
│   │       └── MyClass.java
│   └── resources/
│       ├── config.properties
│       ├── data/
│       │   └── example.txt
│       ├── images/
│       │   └── logo.png
│       └── user.json

重要提示:

  1. 资源文件位置:放在 src/main/resources/ 目录下的文件会被自动复制到classpath中

  2. 路径注意事项

    • getResourceAsStream("file.txt") 从classpath根目录查找
    • getResourceAsStream("/file.txt") 同样从classpath根目录查找(仅Class有此用法)
    • ClassLoader的方法不能以"/"开头
  3. 资源清理:使用try-with-resources自动关闭InputStream

  4. 编码问题:读取文本文件时建议指定字符编码(如UTF-8)

  5. Null检查:始终检查InputStream是否为null,表示资源未找到

  6. Maven项目:resources目录下的文件会自动打包到JAR/WAR中

选择哪种方法取决于你的具体需求,但最常用和最推荐的是 Class.getResourceAsStream() 方法,因为它简单直观且适用于大多数场景。

抱歉,评论功能暂时关闭!