首頁 > Java > java教程 > 主體

如何在Java中使用路徑類別或自訂方法組合路徑?

Mary-Kate Olsen
發布: 2024-10-24 03:41:31
原創
956 人瀏覽過

How to Combine Paths in Java Using Path Class or Custom Method?

在Java 中組合路徑

C#/.NET for Java 中的System.IO.Path.Combine() 等效項是Path Java 7 中引入並在Java 8 中擴充的類別。 Path 類別提供檔案系統路徑的類型安全表示,提供諸如解析之類的方法來組合多個路徑元件。

要使用Path 組合路徑,透過提供多個字串參數來實例化Path 物件:

<code class="java">Path path = Paths.get("foo", "bar", "baz.txt");</code>
登入後複製

對於Java 7 之前的環境,您可以使用File 類別:

<code class="java">File baseDirectory = new File("foo");
File subDirectory = new File(baseDirectory, "bar");
File fileInDirectory = new File(subDirectory, "baz.txt");</code>
登入後複製

透過呼叫以字串形式擷取路徑getPath():

<code class="java">String combinedPath = fileInDirectory.getPath();</code>
登入後複製

或者,您可以使用以下自訂方法來模擬Path.Combine 的行為:

<code class="java">public static String combine(String path1, String path2) {
    File file1 = new File(path1);
    File file2 = new File(file1, path2);
    return file2.getPath();
}</code>
登入後複製

以上是如何在Java中使用路徑類別或自訂方法組合路徑?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!