- 绝对路径
- 类路径
- 通过类加载器获取src路径
在读取文件路径时,万能的方法就是使用绝对路径,但是不建议使用,因为不同开发者所以使用的项目和资源路径必定不同,代码的移植性很低。
@Test
public void test1() throws IOException{
FileReader fr = new FileReader("E:\IDEA\workspace\project01\JavaSE\src\source\jdbc.txt");
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
System.out.println(str);//user=jdbc
br.close();
fr.close();
}
类路径
说明:使用类路径来表示文件的路径一定要从项目的根路径开始写起也就是与src同级的路径。(src全称source)
@Test
public void test2() throws IOException{
//extra.txt文件与src同级
FileReader fr = new FileReader("extra.txt");
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
System.out.println(str);//user=extra
br.close();
fr.close();
}
@Test
public void test2() throws IOException{
FileReader fr = new FileReader("src/demo.txt");
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
System.out.println(str);//user=demo
br.close();
fr.close();
}
通过类加载器获取src路径
testclass.class.getClassLoader() //获取一个类加载器
testclass.class.getClassLoader().getResourceAsStream("xxx");
//获取src下的资源
@Test
public void test6() throws IOException{
Properties pro = new Properties();//集合,map,key=value
//获取class对象
Class clazz = testclass.class;
//获取类加载器
ClassLoader loader = clazz.getClassLoader();
//获取类路径src下的文件
InputStream in = loader.getResourceAsStream("demo.txt");
// InputStream in = loader.getResourceAsStream("source/jdbc.txt");
pro.load(in);
System.out.println(pro);//{user=demo}
System.out.println(pro.getProperty("user"));//demo
}
类加载器详细介绍: https://blog.csdn.net/weixin_46369022/article/details/120685684.



