在编写java代码过程中我们常常会遇到读取外部资源的需求:如读取配置文件等等,通常我们会把配置文件放在项目的classpath路径下或者在web项目的web-inf下。下面我就几种常见的文件读取方式给出事例。
1.从当前的工作目录中读取:
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("workdir.txt")));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
}
2,从classpath中读取(读取找到的第一个符合名称的文件):
try {
InputStream stream = ClassLoader.getSystemResourceAsStream("file.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
}
3,从classpath中读取(读取找到的所有符合名称的文件,如Spring中带有classpath*:前缀的情况就会从classpath中遍历):
try {
Enumeration resourceUrls = Thread.currentThread().getContextClassLoader().getResources("file.txt");
while (resourceUrls.hasMoreElements()) {
URL url = (URL) resourceUrls.nextElement();
System.out.println(url);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
}
} catch (IOException e) {
}
4,从URL中读取:
try {
URL url = new URL("http://blog.csdn.net/sunwp");
System.out.println(url);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
5,web项目从web-inf文件夹读取(通过得到ServletContext读取,可以在servlet或者能够得到request的类中使用):
try {
URL url = (URL) getServletContext().getResource("/WEB-INF/webinffile.txt");
// URL url = (URL)req.getSession().getServletContext().getResource("/WEB-INF/webInfofile.txt");
System.out.println(url);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}