转 JAVA读取外部资源的方法
- - Java - 编程语言 - ITeye博客在java代码中经常有读取外部资源的要求:如配置文件等等,通常会把配置文件放在classpath下或者在web项目中放在web-inf下. 1.从当前的工作目录中读取:. 2,从classpath中读取(读取找到的第一个符合名称的文件):. 3,从classpath中读取(读取找到的所有符合名称的文件,如Spring中带有classpath*:前缀的情况就会从classpath中遍历):.
try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("wkdir.txt"))); String str; while ((str = in.readLine()) != null) { System.out.println(str); } in.close(); } catch (IOException e) { }
try { InputStream stream = ClassLoader.getSystemResourceAsStream("fileinjar.txt"); BufferedReader in = new BufferedReader(new InputStreamReader(stream)); String str; while ((str = in.readLine()) != null) { System.out.println(str); } in.close(); } catch (IOException e) { }
try { Enumeration resourceUrls = Thread.currentThread().getContextClassLoader().getResources("fileinjar.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) { }
try { URL url = new URL("http://blog.csdn.net/kkdelta"); 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(); }
try { URL url = (URL) getServletContext().getResource("/WEB-INF/webinffile.txt"); // URL url = (URL)req.getSession().getServletContext().getResource("/WEB-INF/webinffile.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(); }