java 读取resources下的文件方式

本文探讨了Java中读取资源文件的三种常见方法:直接使用文件路径、Spring的ResourceUtils以及ClassPathResource。分别阐述了它们的适用场景和限制,指出在部署后,使用ClassPathResource或Spring的ResourceLoader可以实现跨环境的通用性。对于开发和部署一致性,推荐使用ClassPathResource或结合Spring注解的方式进行资源文件的读取。

1. 使用项目内路径读取,该路径只在开发工具中显示,如:src/main/resources/resource.properties。只能在开发工具中使用,部署之后无法读取。(不通用)

public void read() throws IOException {
	File file = new File("src/main/resources/resource.properties");
	FileInputStream fis = new FileInputStream(file);
	InputStreamReader isr = new InputStreamReader(fis);
	BufferedReader br = new BufferedReader(isr);
	String data = null;
	while((data = br.readLine()) != null) {
		System.out.println(data);
	}
	
	br.close();
	isr.close();
	fis.close();
}

2. 使用org.springframework.util.ResourceUtils读取,在linux环境中无法读取。(不通用)

public void read2() throws IOException {
	File file = ResourceUtils.getFile("classpath:resource.properties");
	FileInputStream fis = new FileInputStream(file);
	InputStreamReader isr = new InputStreamReader(fis);
	BufferedReader br = new BufferedReader(isr);
	String data = null;
	while((data = br.readLine()) != null) {
		System.out.println(data);
	}
	
	br.close();
	isr.close();
	fis.close();
}

3. 使用org.springframework.core.io.ClassPathResource, 各环境都能读取。(通用)

public void testReadFile() throws IOException {
	//  ClassPathResource classPathResource = new ClassPathResource("resource.properties");
	Resource resource = new ClassPathResource("resource.properties");
	InputStream is = resource.getInputStream();
	InputStreamReader isr = new InputStreamReader(is);
	BufferedReader br = new BufferedReader(isr);
	String data = null;
	while((data = br.readLine()) != null) {
		System.out.println(data);
	}
	
	br.close();
	isr.close();
	is.close();
}

4. 结合spring注解,使用org.springframework.core.io.ResourceLoader。(通用)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

    @Autowired
    ResourceLoader resourceLoader;
    
    
    @Test
    public void testReaderFile() throws IOException {
        Resource resource = resourceLoader.getResource("classpath:resource.properties");
        InputStream is = resource.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String data = null;
        while((data = br.readLine()) != null) {
            System.out.println(data);
        }
        
        br.close();
        isr.close();
        is.close();
    }

}

 

 

<think>好的,我现在需要解决用户的问题:如何在Java读取resources目录下的文件。根据用户提供的引用,我需要结合这些资料来给出正确的示例和方法。 首先,用户引用了四篇资料,其中前三篇都是关于Java读取资源文件的方法,第四篇是关于JD-GUI的Java版本错误,可能和当前问题关系不大,暂时忽略。 引用[1]提到使用ClassLoader的getResource方法获取文件路径,然后创建File对象。示例代码是: ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("file/test.xml").getFile()); 引用[2]提到使用getResourceAsStream方法,示例是InputStream input = getClass().getResourceAsStream(...)。 引用[3]展示了使用try-with-resources和ClassLoader的getResourceAsStream来读取资源文件,例如: try (InputStream is = Main.class.getClassLoader().getResourceAsStream("images/Logo.png")) { ... } 接下来,我需要综合这些方法,给出正确的示例。需要注意的是,当资源文件被打包到JAR中时,直接使用File可能会导致问题,因为资源可能不是实际的文件系统路径。因此,使用InputStream更为可靠。 因此,正确的做法是优先使用getResourceAsStream方法,特别是当应用以JAR形式运行时。此外,需要注意路径的写法,是否以斜杠开头取决于是否使用绝对路径(相对于classpath根)或相对路径(相对于当前类的位置)。 所以,我应该建议用户使用ClassLoader.getResourceAsStream来读取资源,同时提供两种方式:通过类加载器获取绝对路径资源,或者使用相对路径。此外,需要提醒资源路径的正确写法,避免常见错误,比如路径中的斜杠和文件位置是否正确。 可能还需要提到Maven或Gradle项目中resources目录的标准位置,确保文件放置在正确的位置下,例如src/main/resources。此外,处理异常和关闭流也是需要注意的地方,使用try-with-resources可以自动管理资源。 最后,根据用户的要求,生成相关问题,这些问题应该围绕读取资源文件的不同方法、路径处理、异常情况等展开。</think>在Java读取`resources`目录下的文件,可以通过`ClassLoader`或`Class`的`getResourceAsStream`方法实现。以下是具体方法和示例: --- ### 方法1:使用`ClassLoader.getResourceAsStream`(推荐) 适用于读取打包后JAR内的资源文件,路径以**绝对路径**(从`src/main/resources`根目录开始)指定: ```java try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("file/test.txt")) { if (inputStream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } else { System.out.println("文件未找到"); } } catch (IOException e) { e.printStackTrace(); } ``` --- ### 方法2:使用`Class.getResourceAsStream` 适用于**相对路径**(相对于当前类所在包)或绝对路径: ```java // 绝对路径(以'/'开头) try (InputStream inputStream = MyClass.class.getResourceAsStream("/file/test.txt")) { ... } // 相对路径(相对于MyClass所在的包) try (InputStream inputStream = MyClass.class.getResourceAsStream("test.txt")) { ... } ``` --- ### 关键注意事项 1. **路径格式** - 绝对路径:以`/`开头(例如`/config/settings.yml`),对应`src/main/resources`根目录。 - 相对路径:无`/`开头,相对于当前类所在的包路径[^2]。 2. **文件位置** - Maven/Gradle项目中,资源文件应放在`src/main/resources`目录下,编译后会被复制到`target/classes`或`build/resources`中[^1]。 3. **避免使用`File`对象** 资源文件打包到JAR中后,`File`可能无法直接访问,优先使用`InputStream`[^3]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值