1.Springboot以文件的形式获取resources中的文件
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import org.springframework.util.ResourceUtils;
import java.io.*;public static void getResourcesFile() {File file = null;try {file = ResourceUtils.getFile("classpath:cityInfo.json");} catch (FileNotFoundException e) {e.printStackTrace();}JsonParser parse = new JsonParser(); //创建json解析器try {JsonObject json = (JsonObject) parse.parse(new FileReader(file)); //创建jsonObject对象System.out.println(json.toString());} catch (JsonIOException e) {e.printStackTrace();} catch (JsonSyntaxException e) {e.printStackTrace();}catch (FileNotFoundException e) {e.printStackTrace();}}
2.Springboot以流的形式获取resources中的文件
注:当java项目打成jar包,则无法以文件的形式直接获取resources中的文件,此时以流的形式获取
import java.io.*;
import org.springframework.core.io.ClassPathResource;public static void getResourcesByStream() {String str = "";ClassPathResource resource = new ClassPathResource("cityInfo.json");try {InputStream inputStream= resource.getInputStream();//将流转为字符串str = FileUtil.streamToString(inputStream);} catch (IOException e) {e.printStackTrace();}System.out.println(str);}
转至:https://blog.csdn.net/xyy1028/article/details/87785592