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

  

---------------------取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. }  

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值