在Spring框架中,你可以使用Resource接口和ResourceLoader接口来获取位于classpath、文件系统或其他位置的文件。对于resource目录下的文件(这通常指的是类路径下的一个目录),你可以使用ClassPathResource或者直接注入一个Resource类型的bean。
以下是三种常用的方式:
方式一:使用@Value
注解注入资源
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
@Value("classpath:myfile.txt")
private Resource myFile;
public void doSomethingWithFile() throws IOException {
InputStream inputStream = myFile.getInputStream()
// 处理后续业务
}
}
方式二:使用ResourceLoader
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
private final ResourceLoader resourceLoader;
@Autowired
public MyComponent(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
public void doSomethingWithFile() throws IOException {
Resource resource = resourceLoader.getResource("classpath:myfile.txt");
try (InputStream inputStream = resource.getInputStream()) {
// 使用inputStream读取文件内容
}
}
}
方式三:使用PathMatchingResourcePatternResolver
import org.springframework.core.io.PathMatchingResourcePatternResolver;
import org.springframework.core.io.Resource;
import java.io.IOException;
public class MyClass {
public void loadFiles() throws IOException {
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath:*.txt");
for (Resource resource : resources) {
try (InputStream inputStream = resource.getInputStream()) {
// 处理每个文件
}
}
}
}