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

}

}

下面赋上代码对应的文件路径

110f19fe1477616b5f388f9e297e0a70.png

328c890f56fc89dfe8e3e2b6f4017e72.png

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值