我需要將Windows中的文件路徑轉換爲C:\ Documents and Settings \ Manoj \ Desktop for java作爲C:/ Documents and Settings/Manoj/Desktop。文件路徑Windows格式爲java格式
是否有任何實用程序可以這樣轉換?
我需要將Windows中的文件路徑轉換爲C:\ Documents and Settings \ Manoj \ Desktop for java作爲C:/ Documents and Settings/Manoj/Desktop。文件路徑Windows格式爲java格式
是否有任何實用程序可以這樣轉換?
String path = "C:\\Documents and Settings\\Manoj\\Desktop";
path = path.replace("\\", "/");
// or
path = path.replaceAll("\\\\", "/");
找到更多的細節在Docs
+1 - Java **是**實用程序;) – 2010-06-17 06:40:21
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
s爲不可變的。一旦它們被創建,你就不能改變它們。這意味着replace
返回一個新的字符串,其中目標("\\"
)被替換("/"
)替換。只需撥打replace
將不會更改path
。
replaceAll
和replace
之間的區別是,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中,你應該使用4個反斜線但不是兩個。
你能爲什麼需要這個? 因爲通常在文件處理中,java可以自動處理這些轉換...... – Nivas 2010-06-17 06:45:51