spring boot读取txt静态文件
时间: 2023-09-07 19:01:48 浏览: 184
Spring Boot默认会将静态资源文件(如txt文件)放在classpath下的/static、/public和/resources目录中,可以直接访问。以下是几种读取txt静态文件的方法:
1. 使用ClasspathResourceLoader:在Spring Boot中,可以通过ClasspathResourceLoader类来读取classpath下的文件。可以通过以下代码来读取txt文件:
```java
ClassLoader classLoader = getClass().getClassLoader();
Resource resource = new ClassPathResource("static/example.txt");
try {
File file = resource.getFile();
// 读取文件内容
} catch (IOException e) {
e.printStackTrace();
}
```
2. 使用ResourceLoader:在Spring Boot中,可以通过ResourceLoader来加载classpath下的文件。可以通过以下代码来读取txt文件:
```java
@Autowired
private ResourceLoader resourceLoader;
public void readTxtFile() {
Resource resource = resourceLoader.getResource("classpath:static/example.txt");
try {
InputStream inputStream = resource.getInputStream();
// 读取文件内容
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
```
3. 使用文件路径:如果txt文件位于绝对路径下,可以直接使用File类来读取。可以通过以下代码来读取txt文件:
```java
String filePath = "/absolute/path/to/example.txt";
File file = new File(filePath);
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
// 读取文件内容
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
```
以上是使用Spring Boot读取txt静态文件的几种方法,根据具体情况选择合适的方法来实现。
阅读全文
相关推荐


















