温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

浅谈java 中文件的读取File、以及相对路径的问题

发布时间:2020-10-07 11:57:53 来源:脚本之家 阅读:151 作者:枫叶 栏目:编程语言

一、对于java项目中文件的读取

1、使用System 或是 系统的Properties对象

①直接是使用 String relativelyPath=System.getProperty("user.dir");

②使用Properties对象

我们先来遍历一下系统的属性:

Properties properties = System.getProperties();
Enumeration pnames = properties.propertyNames();
while (pnames.hasMoreElements()) {
String pname = (String) pnames.nextElement();
System.out.print(pname + "--------------");
System.out.println(properties.getProperty(pname));
}

这是系统的属性,由此其实还是绕到使用 user.dir 属性来取得当前项目的真是路径

通过 String relativelyPath = properties.getProperty("user.dir"); 取得

我自己的电脑上面的项目 Log4jProj 的真是路径是 :

user.dir--------------D:\Develop\workspace\ws_self\10_ws_eclipse_j2ee_mars\Log4jProj

其实方式①和方式②一个意思,殊途同归

2、第二种方式:使用当前类的类加载器进行获取 ClassLoader

首先来回顾一下,如何获取Class字节码实例,三种方式:(比如我的类叫Demo)

① Demo.class

② Class.forName("类的全称")

③ 利用Demo的实例对象,调用对象的getClass()方法获取该对象的Class实例

回顾了如何获取Class字节码实例之后,然后再来回顾一下,如何获取ClassLoader对象

① Demo.class.getClassLoader()

② Class.forName("类的全称").getClassLoader()

③ 假设demo为Demo的实例化对象 demo.getClass().getClassLoader()

④ 通过Thread对象的getContextClassLoader() 方法来获取

Thread.currentThread().getContextClassLoader()

进入正题:

有了ClassLoader对象之后,我们这么时候通过ClassLoader对象来获取java项目中的文件

首先让大家看下我当前的项目目录结构

以及实际文件的目录结构

需求就是,此时Test需要读取 log4j.properties 文件的路径

用到ClassLoader的两个方法,一个是静态的一个非静态的

输出结果:

记住哦,这里的getSystemResource方法获取的是URL对象,需要调用getPath()方法获取路径

1、当只是获取 log4j.properties 文件输入流的时候可以通过以下两种方式

① 依然是使用 ClassLoader, 其中有两个方法,两者一个是静态一个非静态

ClassLoader.getSystemResourceAsStream("config/log4j.properties");

Thread.currentThread().getContextClassLoader().getResourceAsStream("config/log4j.properties");

② 先通过File文件包装之后,然后新建一个输入流

File file01 = new File("config/log4j.properties");
System.out.println(file01.getAbsolutePath());

File file02 = new File(properties.getProperty("user.dir") + "/bin/config/log4j.properties");
System.out.println(file02.getAbsolutePath());

//ClassLoader.getSystemResource获取的是URL对象
File file03 = new File(ClassLoader.getSystemResource("config/log4j.properties").getPath());
System.out.println(file03.getAbsolutePath());

其中创建file03 的方式不建议采纳,因为getSystemResource方法如果没获取到文件,则得到的

URL对象为null,此时再调用getPath()就会报错

如果有了文件对象就可以直接创建流了,此处不作赘述

以上这篇浅谈java 中文件的读取File、以及相对路径的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI