java中擷取路徑的幾種基本的方法,java擷取路徑幾種

來源:互聯網
上載者:User

java中擷取路徑的幾種基本的方法,java擷取路徑幾種

package com.ygh.blog.realpath;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.net.URL;import java.util.Properties;/** * 擷取java下面的路徑的示範 */import org.junit.Test;public class RealPathTest {    /**     * 擷取當前類所在的工程路徑     */    @Test    public void fun1() {        File file = new File(this.getClass().getResource("/").getPath());        // D:\project\taotaoshop\src\blog-mybatis1\target\test-classes        System.out.println(file);    }    /**     * 擷取當前類的絕對路徑     */    @Test    public void fun2() {        File file = new File(this.getClass().getResource("").getPath());        // D:\project\taotaoshop\src\blog-mybatis1\target\test-classes\com\ygh\blog\realpath        System.out.println(file);    }    /**     * 擷取當前類所在的工程路徑,兩種方法皆可     *      * @throws IOException     */    @Test    public void fun3() throws IOException {        File file = new File("");        String path = file.getCanonicalPath();        // D:\project\taotaoshop\src\blog-mybatis1        System.out.println(path);        // D:\project\taotaoshop\src\blog-mybatis1        System.out.println(System.getProperty("user.dir"));    }    /**     * 擷取當前src下面的檔案的路徑     */    @Test    public void fun4() {        URL url = this.getClass().getClassLoader().getResource("jdbc.properties");        System.out.println(url);    }    /**     * 擷取其他源碼包下面的檔案路徑     */    @Test    public void fun5() {        // 使用這種方法可以擷取路徑        URL url = this.getClass().getClassLoader().getResource("test2.txt");        // file:/D:/project/taotaoshop/src/blog-mybatis1/target/classes/test.txt        System.out.println(url);    }    @Test    public void fun6() throws Exception {        URL url = this.getClass().getClassLoader().getResource("test2.txt");        System.out.println(url.getPath());        Properties properties = new Properties();        // 使用這種方式可以擷取檔案對應的輸出資料流        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");        properties.load(inputStream);        File file = new File(url.getPath());        System.out.println(properties.get("jdbc.driverClassName"));    }}

下面賦上代碼對應的檔案路徑

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.