I am saving the Multipart file and I am using the Path
class Of java.nio.file.Path
.And in this Path
I am getting the path C:\for\expample\
but I need the path like this C:/for/expample/
. Here I am sharing my code where I have tried to do but unfortunately, I didn't get the true path with forwarding slashes.
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");
}
}
try
return fPath == null ? "" : fPath.normalize().toString().replace("\\","/");
Convert the full path to a string and use the regular expression like
String str = fPath.toString();
str = str.replace("\\", "/");
Given a Path
object having C:\\aaaa\\bbbb
, simply replace all double-blackslashes with a forward slash
path.toString().replaceAll("\\\\", "/");
Output: C:/aaaa/bbbb
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.