springboot怎么讀取相對(duì)路徑文件

小億
685
2023-09-28 17:18:46
欄目: 編程語言

在Spring Boot中,可以使用ResourceLoader來讀取相對(duì)路徑文件??梢詫⑽募胖迷陧?xiàng)目的resources目錄中,然后使用ResourceLoader讀取該文件。

以下是一個(gè)示例:

import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@Component
public class FileHelper {
private final ResourceLoader resourceLoader;
public FileHelper(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
public String readFile(String filePath) throws IOException {
Resource resource = resourceLoader.getResource(filePath);
BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
}
reader.close();
return content.toString();
}
}

在上述示例中,FileHelper通過構(gòu)造函數(shù)注入了ResourceLoader,然后使用resourceLoader.getResource(filePath)獲取相對(duì)路徑文件的Resource對(duì)象。接下來,使用Resource對(duì)象的getInputStream()方法獲取文件的輸入流,并使用BufferedReader逐行讀取文件內(nèi)容。最后,將文件內(nèi)容轉(zhuǎn)換為字符串并返回。

你可以在任何Spring組件中使用FileHelper來讀取相對(duì)路徑文件:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.CommandLineRunner;
import java.io.IOException;
@SpringBootApplication
public class MyApplication implements CommandLineRunner {
private final FileHelper fileHelper;
@Autowired
public MyApplication(FileHelper fileHelper) {
this.fileHelper = fileHelper;
}
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Override
public void run(String... args) throws IOException {
String content = fileHelper.readFile("classpath:example.txt");
System.out.println(content);
}
}

在上述示例中,MyApplication使用@Autowired注解將FileHelper注入到MyApplication中。在run方法中,調(diào)用fileHelper.readFile("classpath:example.txt")來讀取resources目錄下的example.txt文件,并輸出文件內(nèi)容。

需要注意的是,classpath:前綴是用于指定相對(duì)路徑文件的前綴,確保正確地從resources目錄中讀取文件。

0