首頁 类库下载 java类库 java中獲取路徑的幾種基本的方法

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

Oct 11, 2016 pm 04:41 PM

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"));
    }

}
登入後複製

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

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

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

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)