标签:ref test red conf ade 方法 ring extc amr
java读取Resources下文件http://www.fu-w.com/a/63645.html
第一种,读为流文件
InputStream path = this.getClass().getResourceAsStream("/data.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(path));
第二种, 读取路径
Thread.currentThread().getContextClassLoader()。
URL l1 =
Thread.currentThread().getContextClassLoader().getResource("readFile/test1.xml");
System.out.println(l1);
URL l2 =
Thread.currentThread().getContextClassLoader().getResource("collection/test2.xml");
System.out.println(l2);
URL l3 = Thread.currentThread().getContextClassLoader().getResource("test3.xml");
String l4=l3.getPath();//加上getPath()则去掉前面的file:
System.out.println(l3); // file:/F:/demo/Studying/out/production/Studying/test3.xml
System.out.println(l4);// /F:/demo/Studying/out/production/Studying/test3.xml
第三种, 读为流文件
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("conf/job_two_one_mapping.txt");
try(Scanner scanner = new Scanner(is)) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (Exception e) {
log.error("读取文件数据异常" ,e);
}
第四种, 读取路径
ResourceBundle bundle = ResourceBundle.getBundle("config");
String url = bundle.getString("url");
该方法默认读取的是resources文件夹下的以.properties为后缀的文件,代码中的例子即为config.properties
第五种, 读为流文件
InputStream inputStream = Resources.class.getResourceAsStream(“/mybatis.xml”);或者
InputStream resourceAsStream = Resources.class.getClassLoader().getResourceAsStream("a.py");
第六种, 读取路径
URL resource = Resources.class.getClassLoader().getResource("");
String path = resource.getPath();
底层如下:
public static URL getResource(String resourceName) {
ClassLoader loader = MoreObjects.firstNonNull(
Thread.currentThread().getContextClassLoader(),
Resources.class.getClassLoader());
URL url = loader.getResource(resourceName);
checkArgument(url != null, "resource %s not found.", resourceName);
return url;
}
文章分享完毕,希望我的分享对大家有所帮助。更多学习技巧也可参阅:福网
标签:ref test red conf ade 方法 ring extc amr
原文地址:https://www.cnblogs.com/meilideni/p/13059859.html