Java上传文件保存到指定路径
上代码
@PostMapping("/file-upload")
@ApiOperation(value = "上传swagger.json", httpMethod = "POST")
public String fileUpload(@ApiParam(value = "swaggerJsonFile", required = true) @RequestParam(value = "swaggerJsonFile") MultipartFile freeMarkerFile) {
OutputStream os = null;
InputStream inputStream = null;
//保存文件的文件名
String fileName = "swagger.json";
try {
inputStream = freeMarkerFile.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流保存到本地文件
String path = "D:\resources\";//保存到指定的文件目录
File tempFile = new File(path);
if (!tempFile.exists()) {
tempFile.mkdirs();
}
os = new FileOutputStream(tempFile.getPath()+ "/" + File.separator + fileName);
// 开始读取
while ((len = inputStream.read(bs)) != -1) {
os.write(bs, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 完毕,关闭所有链接
try {
os.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return fileName;
}
调用接口获取文本数据,把文本数据保存到本地指定目录
@GetMapping("/get-json")
@ApiOperation(value = "获取swagger.json", httpMethod = "GET")
public String fileImport(@ApiParam(value = "获取swagger.json的url路径", required = true) @RequestParam(required = true) String swaggerDocUrl){
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("utf-8"));
restTemplate.setMessageConverters(Collections.singletonList(converter));
headers.add("Content-Type","application/json");
headers.add("charset","UTF-8");
HttpEntity<Object> entity = new HttpEntity<>(headers);
ResponseEntity<String> exchange = restTemplate.exchange(swaggerDocUrl, HttpMethod.GET, entity, String.class);
String body = exchange.getBody();
FileWriter fileWriter = null;
try {
String path = "D:\resources\";//保存到指定的文件目录
String name = "swagger.json";//保存的文件名
fileWriter = new FileWriter(path + name);
fileWriter.write(body);
fileWriter.flush();
fileWriter.close();
return "获取成功!";
} catch (IOException e) {
e.printStackTrace();
return "获取失败!";
}
}