我正在保存多部分文件,并使用java.nio.file.Path
的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");
}
}
C:
驱动器。 - daniufileNme == ""
,将不起作用。请参见 https://dev59.com/DnRB5IYBdhLWcg3wyqEd。 - VGR