文件路径Windows格式为java格式

我需要在Windows中将文件路径转换为C:\ Documents and Settings \ Manoj \ Desktop for java for C:/ Documents and Settings / Manoj / Desktop。

有没有像这样转换的实用程序。?

String path = "C:\\Documents and Settings\\Manoj\\Desktop"; path = path.replace("\\", "/"); // or path = path.replaceAll("\\\\", "/"); 

在文档中查找更多详细信息

 String path = "C:\\Documents and Settings\\Manoj\\Desktop"; String javaPath = path.replace("\\", "/"); // Create a new variable 

要么

 path = path.replace("\\", "/"); // Just use the existing variable 

String是不可变的。 创建它们后,您无法更改它们。 这意味着replace返回一个新的String,其中目标( "\\" )被替换( "/" )替换。 简单地调用replace不会改变path

replaceAllreplace之间的区别在于replaceAll将搜索正则表达式,替换不会。

Java 7及更高版本支持Path类(在java.nio包中)。 您可以使用此类将字符串路径转换为适用于当前操作系统的路径。

使用:

 Paths.get("\\folder\\subfolder").toString() 

在Unix机器上,会给你/folder/subfolder 。 另一种方式也是如此。

https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

 String path = "C:\\Documents and Settings\\someDir"; path = path.replaceAll("\\\\", "/"); 

在Windows中,您应该使用四个反斜杠而不是两个。