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

取类路径中的资源,取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));

 

	public static void main(String[] args) throws Exception {
		String path="d:\\计算.txt";
		File file=new File(path);
		FileInputStream in=new FileInputStream(file);
		//文本文件编码是UTF-8,如果是其它,请修改下面
		InputStreamReader read = new InputStreamReader(in, "UTF-8");
		BufferedReader ra = new BufferedReader(read);
		String s=ra.readLine();
		while(s!=null){
			System.out.println(s);
			s=ra.readLine();
		}
	}