[英]How to replace backSlash (\) with the forwardSlash(/) in `java.nio.file.Path`?
I am saving the Multipart file and I am using the Path
class Of java.nio.file.Path
in this Path
I am getting the path C:\for\expample\
but I need the path like this 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");
}
}
嘗試
return fPath == null ? "" : fPath.normalize().toString().replace("\\","/");
將完整路徑轉換為字符串並使用正則表達式,例如
String str = fPath.toString();
str = str.replace("\\", "/");
給定Path
object 具有C:\\aaaa\\bbbb
,只需將所有雙黑斜杠替換為正斜杠
path.toString().replaceAll("\\\\", "/");
Output: C:/aaaa/bbbb
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.