欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

java获取各种路径的基本方法

时间:2021-05-27 08:41:57|栏目: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"));
 }

}

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

上一篇:Java的字符读写类CharArrayReader和CharArrayWriter使用示例

栏    目:JAVA代码

下一篇:详解Java如何进行Base64的编码(Encode)与解码(Decode)

本文标题:java获取各种路径的基本方法

本文地址:http://www.codeinn.net/misctech/129564.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有