java读取资源下的文件
第一,把它读成流文件
InputStream path=this.getClass ().getresourceasstream ) )/data.txt );
bufferedreaderreader=newbufferedreader (newinputstreamreader (path );
1
2
第二个是读取路径
Thread.currentThread ().getContextClassLoader ) )。
URL l1=
Thread.currentThread ().getContextClassLoader ).get resource (' readfile/test1.XML ' );
system.out.println(L1;
URL l2=
Thread.currentThread ().getContextClassLoader ).get resource (' 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
1
2
3
4
5
6
7
8
9
10
11
12
13
第三,将其作为流文件阅读
inputstream is=thread.current thread (.getcontextclassloader ).getresourceasstream (' conf/job _ two _ one _ mmone )
try (扫描仪扫描仪=新扫描仪(is ) ) }
while(Scanner.Hasnextline () ) ) )。
system.out.println (scanner.nextline ();
}
}catch(exceptione ) {
log.error (“读取文件数据异常”,e );
}
1
2
3
4
5
6
7
8
第四个是读取路径
resourcebundlebundle=resource bundle.get bundle (config );
string URL=bundle.getstring (' URL );
1
2
缺省情况下,此方法读取资源文件夹下以. properties为后缀的文件。 代码的示例是config.properties
第五,作为流文件阅读
inputstream inputstream=resources.class.getresourceasstream (“/my batis.XML”); 或者
inputstreamresourceasstream=resources.class.getclass loader ().getresourceasstream('a.py ' );
1
2
第六,读取路径
URL resource=resources.class.getclass loader ().getResource (' ' );
String path=resource.getPath (;
下面的层次结构如下:
公共资源名称。
class loader loader=more objects.first nonnull (
Thread.currentThread ().getContextClassLoader ) )、
Resources.class.getClassLoader ();
URL URL=loader.get resource (资源名称;
检查协议(URL!=null,' resource %s not found.',resourceName;
返回URL;
}
————————————————
这是CSDN博客的《世界,你好》原创文章,符合CC 4.0 BY-SA版权协议。 请附上原文来源的链接和本声明。
原文链接: https://blog.csdn.net/QQ _ 41622739/article/details/97819146