如何获取文件的绝对路径


package com.day06;

/**
* @author anyan
* @date 2021/5/25-15:50
*/
/*
如何获取文件的绝对路径?以下方式有一个前提:文件必须在类路径,即src路径下。
//
*/
public class AboutPath {
public static void main(String[] args) {
//Thread.currentThread() 当前线程
//get.ContextClassLoader() 类加载器
//getResource() 获取文件,此文件必须位于类路径下,即src目录下.默认从类路径下作为起点
//getPath() 获取绝对路径
//总结:通过当前线程下的类加载器下的获取源文件方法获取文件的绝对路径
/* String path=Thread.currentThread().getContextClassLoader().getResource("classinfor.properties").getPath();
System.out.println(path);*/
String path1=Thread.currentThread().getContextClassLoader().getResource("myfile.properties").getPath();
System.out.println(path1);
String path2=Thread.currentThread().getContextClassLoader().getResource("com/day06/myfile.text").getPath();
System.out.println(path2);
}
}

/*
方法2
*/
package com.day06;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
* @author anyan
* @date 2021/5/25-17:02
*/
/*
读取文件时以流的形式返回
*/
public class PathTest {
public static void main(String[] args) throws IOException {
InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream("com/day06/classinfor.properties");
Properties pro=new Properties();
pro.load(in);
String s1=pro.getProperty("userName");
System.out.println(s1);
}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM