2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > java 相对路径获取_在java项目中通过相对路径获取资源的方式

java 相对路径获取_在java项目中通过相对路径获取资源的方式

时间:2022-12-09 00:54:24

相关推荐

java 相对路径获取_在java项目中通过相对路径获取资源的方式

1.可以通过 类名.class.getResource方法获取或者getSystemResource

2.可以通过当前线程 Thread.currentThread().getContextClassLoader().getResource获取

public class TestDemo {

public static void main(String[] args) throws FileNotFoundException, IOException {

Properties pro=new Properties();

TestDemo test=new TestDemo();

pro.setProperty("url", "localhost:8080");

pro.setProperty("username", "root");

pro.setProperty("password", "123");

String filepath="G:/util/";

//pro.store(new FileOutputStream(new File("db.properties")), "资 源配置");

File file =new File(filepath);

if(!file.exists()){

file.mkdir();

}

File realpath=new File(file,"db.properties");

if(!realpath.exists()){

realpath.createNewFile();

}

//写入properties文件

pro.store(new FileOutputStream(realpath), "properties配置");

File xmlpath=new File(file,"db.xml");

if(!xmlpath.exists()){

xmlpath.createNewFile();

}

//写入xml文件中

pro.storeToXML(new FileOutputStream(xmlpath), "xml配置");

//加载配置文件

Properties pro1=new Properties();

// pro1.load(TestDemo.class.getClassLoader().getResourceAsStream("test/db.properties"));

//获取文件的相对路径

//1.可以通过 类名。class.getResource方法获取或者getSystemResource

//2.可以通过当前线程 Thread.currentThread().getContextClassLoader()。getResource获取

pro1.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("test/db.properties"));

System.out.println(TestDemo.class.getResource("/test/db.properties"));

System.out.println(Thread.currentThread().getContextClassLoader().getResource("test/db.properties"));

//System.out.println(Thread.currentThread().getContextClassLoader().getSystemResource("test/db.properties"));

System.out.println(test.getClass().getClassLoader().getResourceAsStream("test/db.properties"));

System.out.println(TestDemo.class.getResource("/"));//斜杠代表从根路径 开始

System.out.println(TestDemo.class.getResource(""));//空格代表当前类的相对路径开始

System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));//空格代表从根路径开始

String str= pro1.getProperty("password", "没找到");

System.out.println(str);

} }

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。