您的位置:首页 > 其它

取Servlet上下文路径,取WebContent的路径

2012-09-25 17:14 351 查看
博客分类:

Servlet/Jsp

---------------------取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代码



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();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: