从网上找了很读取的方法但是没有那种简单方便易于理解的读取方式,今天本人将个人理解发表。
提示:只读取项目中的文件
为什么要读取文件:项目需要加载文件中的数据
方法一:使用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; } }
项目包路径: