配置在resource目录下
public List<String> getTextMethod1() {
// 读取配置文件
List<String> list = new ArrayList<>();
// 从AppClassLoader类加载器获取资源
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("static/area.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
try {
while ((line = reader.readLine()) != null) {
list.add(line);
}
} catch (Exception e) {
throw new RuntimeException("获取异常!");
} finally {
try {
reader.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
public List<String> getTextMethod2() {
List<String> list;
try {
Resource resource = new ClassPathResource("static/area.txt");
Path myAllowWordsPath = Paths.get(resource.getFile().getPath());
list = Files.readAllLines(myAllowWordsPath, StandardCharsets.UTF_8);
} catch (IOException ioException) {
throw new RuntimeException("获取异常!");
}
return list;
}
package com.saas.xxx.controller;
import com.saas.xxx.common.AjaxResult;
import io.swagger.annotations.Api;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
/**
* @author : Cookie
* date : 2023/12/18
*/
@RestController("/textArea")
@Api(tags = "测试获取静态文件")
public class TextAreaController {
@GetMapping("/getText1")
public AjaxResult getText1() {
return AjaxResult.success(getTextMethod1());
}
@GetMapping("/getText2")
public AjaxResult getText2() {
return AjaxResult.success(getTextMethod2());
}
// 方式一
public List<String> getTextMethod1() {
// 读取配置文件
List<String> list = new ArrayList<>();
// 从AppClassLoader获取资源
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("static/area.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
try {
while ((line = reader.readLine()) != null) {
list.add(line);
}
} catch (Exception e) {
throw new RuntimeException("获取异常!");
} finally {
try {
reader.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
// 方式二
public List<String> getTextMethod2() {
List<String> list;
try {
Resource resource = new ClassPathResource("static/area.txt");
Path myAllowWordsPath = Paths.get(resource.getFile().getPath());
list = Files.readAllLines(myAllowWordsPath, StandardCharsets.UTF_8);
} catch (IOException ioException) {
throw new RuntimeException("获取异常!");
}
return list;
}
}