java获取各种路径的基本方法
java获取各种路径的基本方法
发布时间:2016-12-28 来源:查字典编辑
摘要:本文实例为大家分享了java获取不同路径的方法,供大家参考,具体内容如下packagecom.ygh.blog.realpath;impor...

本文实例为大家分享了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:projecttaotaoshopsrcblog-mybatis1targettest-classes System.out.println(file); } /** * 获取当前类的绝对路径 */ @Test public void fun2() { File file = new File(this.getClass().getResource("").getPath()); // D:projecttaotaoshopsrcblog-mybatis1targettest-classescomyghblogrealpath System.out.println(file); } /** * 获取当前类所在的工程路径,两种方法皆可 * * @throws IOException */ @Test public void fun3() throws IOException { File file = new File(""); String path = file.getCanonicalPath(); // D:projecttaotaoshopsrcblog-mybatis1 System.out.println(path); // D:projecttaotaoshopsrcblog-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获取各种路径的基本方法1

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持查字典教程网。

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新Java学习
热门Java学习
编程开发子分类