Java 相當於C# 的System.IO.Path.Combine()
C# 中的System.IO.Path.Combine()方法將多個字串組合成一個路徑。在 Java 中,有多種方法可以實現類似的功能,具體取決於您的 Java 版本和偏好設定。
Java 7 和 Java 8:
對於 Java 7 和 Java 8、建議的選項是使用java.nio.file.Path類別。 Path.resolve() 方法可讓您組合路徑和字串。例如:
Path path = Paths.get("foo", "bar", "baz.txt");
Java 7 之前的環境:
對於Java 7 之前的環境,java.io.File 類別提供了一些組合路徑的功能。您可以透過重複呼叫 new File() 建構子來建立層次結構:
File baseDirectory = new File("foo");
File subDirectory = new File(baseDirectory, "bar");
File fileInDirectory = new File(subDirectory, "baz.txt");
模仿Path.Combine() 與Java 的File Class:
模仿Path 的行為. Combine() 更緊密地,您可以建立一個靜態方法,將java.io.File 物件轉換為字串:
public static String combine(String path1, String path2) {
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3