JAVA获取文件的几种常用方式

来源:互联网 发布:mysql 安装 编辑:程序博客网 时间:2024/06/13 11:13

1、user.dir

System.out.println(System.getProperty("user.dir"));

此方获取的是运行的路

比如

1、

2、如果在eclipse上运行则是eclipse运行文件同级


3、tomcat则在


4、File file = new File("log4j.properties");

这里的log4j.properties也是在以上类型的目录下查找

 

5、FileInputStreaminput = newFileInputStream("log4j.properties");

与File一样,在运行路径上找文件

2、获取绝对路径

方法 String in = LogUtil.class.getResource("/").getPath();

或者:this.getClass().getClassLoader().getResource("/").getPath()

结果:

/E:/temp/springmvc/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/rentBook/WEB-INF/classes/

 

LogUtil.class.getResource("/").getPath(); 加个”/”就会打印classes下的绝对路径

LogUtil.class.getResource("").getPath(); 就会显示classes + 包名

 

Tomcat打印如下:

 

WEB工程

this.getServletContext().getRealPath("/")

返回:

工程的绝对路径/返回的也称为“根”

比如工程:

Book

|_WEB-INF

|_xx.properties

返回d:\Book\

3、相对路径:

InputStream input = LogUtil.class.getResourceAsStream("/log4j.properties");

 

读取的是src/log4j.properties 下的文件

 

InputStream input = LogUtil.class.getResourceAsStream("log4j.properties");

 

读取的是 与LogUtil同级的log4j.properties

 

第二种:

getServletConfig().getServletContext()  
                .getResourceAsStream("report1.jasper")

访问的是根路径


Book

|_WEB-INF

|_xx.properties

|_report1.jasper


 

 

0 0