码迷,mamicode.com
首页 > 编程语言 > 详细

(转)JAVA读取外部资源的方法

时间:2014-05-15 17:56:22      阅读:340      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   c   

在java代码中经常有读取外部资源的要求:如配置文件等等,通常会把配置文件放在classpath下或者在web项目中放在web-inf下.

1.从当前的工作目录中读取:

bubuko.com,布布扣
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) {}
bubuko.com,布布扣

2.从classpath中读取(读取找到的第一个符合名称的文件):

bubuko.com,布布扣
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) {}
bubuko.com,布布扣

3.从classpath中读取(读取找到的所有符合名称的文件,如Spring中带有classpath*:前缀的情况就会从classpath中遍历):

bubuko.com,布布扣
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) {}
bubuko.com,布布扣

4.从URL中读取:

bubuko.com,布布扣
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();
}
bubuko.com,布布扣

5.web项目从web-inf文件夹读取(通过得到ServletContext读取,可以在servlet或者能够得到request的类中使用):

bubuko.com,布布扣
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();
}
bubuko.com,布布扣

以上代码在eclipse环境中运行测试过.不过最近在用JUnit的时候,通过ant运行JUnit时通过ClassLoader.getSystemResourceAsStream("file.txt");的方式去找不到文件.改成 Xclass.class.getClassLoader().getResourceAsStream("file.txt");能从ant指定的classpath中找到文件.

 

原文链接:http://blog.csdn.net/kkdelta/article/details/5560210

(转)JAVA读取外部资源的方法,布布扣,bubuko.com

(转)JAVA读取外部资源的方法

标签:style   blog   class   code   java   c   

原文地址:http://www.cnblogs.com/kentyouyou/p/3729804.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!