JAVA获取工程内文件

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");

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值