如何在`java.nio.file.Path`中将反斜杠(\)替换为正斜杠(/)?

3

我正在保存多部分文件,并使用java.nio.file.PathPath类。在这个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");
        }
    }

1
为什么你需要这样的路径?它不是一个正确格式的Windows路径。 - daniu
有两个文件,即“系统文件”和“应用程序文件”,我必须将它们保存在客户端电脑的特定文件夹中。在我的本地服务器上,所有文件都已成功保存在特定文件夹中,运行良好。但是,在AWS服务器上运行时,我遇到了错误,显示“存储文件时出错”。我不知道为什么会发生这种情况?! - Rajan
对于AWS而言,我怀疑反斜杠并不是你唯一的问题。虽然我没有在上面工作过很多,但我怀疑它不提供C:驱动器。 - daniu
如果 fileNme == "",将不起作用。请参见 https://dev59.com/DnRB5IYBdhLWcg3wyqEd。 - VGR
3个回答

3

尝试

return fPath == null ? "" : fPath.normalize().toString().replace("\\","/");


谢谢你的帮助!!我已经尝试过这个,但它没有起作用。 - Rajan
请问您能否提供一下您的fPath的样例字符串? - Kishita Variya
fPath: D:\test-root\SLT\env_files\16-10-2019。16-10-2019是我的环境名称,两个文件都保存在其中。 - Rajan
理想情况下,如果是字符串,它应该像D:\\test-root\\SLT\\env_files\\16-10-2019这样,因为\t等具有不同的含义。 - Kishita Variya
但它不会将反斜杠转换为正斜杠。我必须在基于Linux的AWS上运行,在AWS Linux中它只读取正斜杠。 - Rajan

0

给定一个 Path 对象,其值为 C:\\aaaa\\bbbb,只需将所有的双反斜杠替换为正斜杠即可。

path.toString().replaceAll("\\\\", "/");

输出:C:/aaaa/bbbb


0
将完整路径转换为字符串并使用正则表达式。
String str = fPath.toString();
str = str.replace("\\", "/");

谢谢你的帮助,伙计。我需要发送 java.nio.file.PathPath 类,而不是字符串。 - Rajan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接