1.获取maven工程下src/main/resources下的文件,如下图所示
场景:
代码:
/**
* 获取src/main/resources下文件
*
* @throws Exception
*/
public void t1() throws Exception{
//这里是使用类加载器来获取的文件路径,类加载器会从target/classes下寻找参数中给定的文件
String path = Test.class.getClassLoader().getResource("config/test/AA.txt").getPath();
System.out.println("文件的磁盘路径为:"+path);
//打印出文件内容
File file = new File(path);
PrintFileContext(file);
}
/**
* 将文件内容打印出来
*
* @param file
* @throws Exception
*/
public static void PrintFileContext(File file) throws Exception{
InputStream in = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
String line = "";
while(true){
line = br.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
br.close();
}
测试:
2.获取包内文件
场景:
代码:
/**
* 获取包内文件
*
* @throws Exception
*/
public void t2() throws Exception{
//这种方式默认会从指定类所在的位置查找参数中给定的文件,但是如果加了/ 他也会从target/classes下寻找文件
String path = Test.class.getResource("/app/test/BB.txt").getPath();
System.out.println("文件的磁盘路径为:"+path);
//打印出文件内容
File file = new File(path);
PrintFileContext(file);
}
测试:
3.获取webapp下的文件
场景:
代码:
/**
* 获取webapp下的文件内容
*
* @throws Exception
*/
public void t3() throws Exception{
//获取工程所在的根目录
String path = System.getProperty("user.dir");
System.out.println(path);
//将路径中的\转为/,因为\是JAVA的转义字符直接使用会报错
path = path.replaceAll("\\\\", "/");
System.out.println(path);
//获取webapp下我想获取的那个文件
String filePath = path+"/src/main/webapp/resource/CC.txt";
System.out.println(filePath);
//打印出文件内容
File file = new File(filePath);
PrintFileContext(file);
}
测试:
4.总结
类加载器获取文件路径:class.getClassLoader().getResource(" xx ").getPath();
类获取文件路径:class.getResource(" /xx ").getPath();
获取工程根目录:System.getProperty("user.dir");