当前位置: 代码迷 >> Web前端 >> 取种路径中的资源,取Servlet上下文路径
  详细解决方案

取种路径中的资源,取Servlet上下文路径

热度:85   发布时间:2013-03-26 09:54:34.0
取类路径中的资源,取Servlet上下文路径

---------------------取Servlet上下文路径,取WebContent的路径 --------------------------------
1、String path = request.getRealPath("/cfg.xml")? (有警告,不建议使用)
2、String path = request.getSession().getServletContext().getRealPath("/cfg.xml");

---------------------读取类路径中的文件 --------------------------------

一、getResource方法
String path = this.getClass().getClassLoader().getResource("/").getPath();

InputStream is =? 类.class.getResource("a.txt").openStream();

?

二、getResourceAsStream方法

InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( "/com/a.txt");//在/com/目录下找文件

InputStream is = ReadCard.class.getResourceAsStream( "a.txt"); //在ReadCard类所在目录找文件

----------------------取类路径测试代码 -------------------------------

请自己写一个EDB类

?

URL s2=EDB.class.getResource("/") ;
System.out.println(s2);

得到的是当前类EDB.class文件的URI目录。不包括自己


URL s3=EDB.class.getResource("") ;

System.out.println(s3);

得到的是当前的classpath的绝对URI路径


URL s4=EDB.class.getClassLoader().getResource("/") ;
System.out.println(s4);


URL s5=EDB.class.getClassLoader().getResource("") ;

System.out.println(s5);


URL s6=Thread.currentThread().getContextClassLoader().getResource("");
System.out.println(s6);


---------------------读取文本文件内容,并正确指定编码 --------------------------------

InputStreamReader 是字节流通向字符流的桥梁
BufferedReader in ?? = new BufferedReader(new InputStreamReader(System.in));

?

Java代码 ?收藏代码
  1. public ? static ? void ?main(String[]?args)? throws ?Exception?{??
  2. ????String?path="d:\\计算.txt" ;??
  3. ????File?file=new ?File(path);??
  4. ????FileInputStream?in=new ?FileInputStream(file);??
  5. ????//文本文件编码是UTF-8,如果是其它,请修改下面 ??
  6. ????InputStreamReader?read?=?new ?InputStreamReader(in,? "UTF-8" );??
  7. ????BufferedReader?ra?=?new ?BufferedReader(read);??
  8. ????String?s=ra.readLine();??
  9. ????while (s!= null ){??
  10. ????????System.out.println(s);??
  11. ????????s=ra.readLine();??
  12. ????}??
  13. }?
  相关解决方案