java类反射读取项目内的文件

从网上找了很读取的方法但是没有那种简单方便易于理解的读取方式,今天本人将个人理解发表。

提示:只读取项目中的文件

为什么要读取文件:项目需要加载文件中的数据

方法一:使用TestPath.class.getResourceAsStream(path)加载数据

如下图中的main引用的方法,该方法有二种读取方式(该Class文件是有目录的):

第一种:path="./文件名称";

第二种:path="/com/zving/regularExpressionEx/test/json.txt";注意:com包前必须/




第二种方法:TestPath.class.getClassLoader().getResourceAsStream(path)


如下图中testMethod方法调用

方法一:path="a.txt" = "./a.txt" 不能是"/a.txt"

方法二:path="./com/zving/regularExpressionEx/test/json.txt"

path="com/zving/regularExpressionEx/test/json.txt"

不能是path="/com/zving/regularExpressionEx/test/json.txt"






总结:使用getClassLoader()与不使用时要看路径最前面是否有/,

如果记不清楚可以测试。



package com.zving.regularExpressionEx.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.junit.Test;

public class TestPath {

	@Test
	public void testMethod() {
		BufferedReader br = null;
		//String path = "./a.txt";
		String path = "./com/zving/regularExpressionEx/test/json.txt";
		try {
			br = new BufferedReader(new InputStreamReader(
					TestPath.class.getClassLoader().getResourceAsStream(path)));
			String line = br.readLine();
			StringBuilder sb = new StringBuilder();
			while (line != null) {
				sb.append(line);
				line = br.readLine();
			}
			System.out.println(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		TestPath t = new TestPath();
		//String json = t.getJsonText("json.txt");
		String json = t.getJsonText("/com/zving/regularExpressionEx/test/json.txt");//这个也可以
		System.out.println(json);
	}

	public String getJsonText(String path) {
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(
					TestPath.class.getResourceAsStream(path)));
			String line = br.readLine();
			StringBuilder sb = new StringBuilder();
			while (line != null) {
				sb.append(line);
				line = br.readLine();
			}
			return sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}






项目包路径:









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值