读json文件可以直接使用下面的方法,这种只能是json文件,txt等会报错
@Test
public void test() throws IOException {
JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream("D:\\files\\jsonSolve\\t.json"), StandardCharsets.UTF_8));
Gson gson = new GsonBuilder().create();
JsonObject fromJson = gson.fromJson(reader, JsonObject.class);
System.out.println(fromJson);
}
//把一个文件中的内容读取成一个String字符串
public static String getStr(File jsonFile){
String jsonStr;
try {
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8);
int ch;
StringBuilder sb = new StringBuilder();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
//将MultipartFile转换为File
public static File MultipartFileToFile(MultipartFile multiFile) {
// 获取文件名
String fileName = multiFile.getOriginalFilename();
if (fileName == null){
return null;
}
// 获取文件后缀
String prefix = fileName.substring(fileName.lastIndexOf("."));
// 若须要防止生成的临时文件重复,能够在文件名后添加随机码
try {
File file = File.createTempFile(fileName, prefix);
multiFile.transferTo(file);
return file;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}