我正在保存多部分文件,并且正在使用类Path。java.nio.file.Path在这个文件中,Path我得到了路径C:\for\expample\,但我需要这样的路径C:/for/expample/。在这里,我分享我尝试过的代码,但不幸的是,我没有得到带有正斜杠的真实路径。
public String saveFile(MultipartFile theFile, String rootPath, String filePath , String fileNme) throws Exception {
try {
Path fPath = null;
if(theFile != null) {
Path path = Paths.get(rootPath, filePath);
if(Files.notExists(path)) {
//Create directory if one does not exists
Files.createDirectories(path);
}
String fileName;
//Create a new file at that location
if(fileNme == "") {
fileName = theFile.getOriginalFilename();
}else {
fileName = fileNme;
}
fPath = Paths.get(rootPath, filePath, fileName);
if(Files.isRegularFile(fPath) && Files.exists(fPath)) {
Files.delete(fPath);
}
StringWriter writer = new StringWriter();
IOUtils.copy(theFile.getInputStream(), writer, StandardCharsets.UTF_8);
File newFile = new File(fPath.toString());
newFile.createNewFile();
try (OutputStream os = Files.newOutputStream(fPath)) {
os.write(theFile.getBytes());
}
}
return this.replaceBackslashes(fPath == null ? "" :fPath.normalize().toString());
}catch (IOException e) {
e.printStackTrace();
throw new Exception("Error while storing the file");
}
}
慕的地6264312
狐的传说
缥缈止盈
相关分类