Java中关于文件路径读取问题的分析

Java读取文件路径

记录一种通用获取文件绝对路径的方法,即使代码换了位置了,这样编写也是通用的:

注意:使用以下方法的前提是文件必须在类路径下,类路径:凡是在src下的都是类路径。

1.拿到User.properties文件的绝对路径:

package com.lxc.domain; import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.util.Properties; public class Test {    public static void main(String[] args) {        try {            /**             * Thread.currentThread() 当前线程对象             * getContextClassLoader() 线程方法,获取的是当前线程的类加载器对象             * getResource("") 这是类加载器对象的方法,当前线程的类加载器默认从类的根路径下加载资源             *             */            String path = Thread.currentThread().getContextClassLoader().getResource("User.properties").getPath();            System.out.println(path);            FileReader reader = new FileReader(path);    }}

2.还可以以流的方式直接获取到文件流,直接加载

package com.lxc.domain; import java.io.IOException;import java.io.InputStream;import java.util.Properties; public class Fanshe {     public static void main(String[] args) {        // 以流的方式读取        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/lxc/domain/userProperties.properties");        Properties properties = new Properties();        try {            properties.load(inputStream);            inputStream.close();            System.out.println(properties.getProperty("username"));        } catch (IOException e) {            e.printStackTrace();        }    }}

这里还要注意一个小点:资源配置文件放到resource文件夹下和放到包路径下,打包编译之后资源文件的存放位置会不一样,放到resource文件夹下打包编译值后的位置在classes文件夹下:

放到包文件夹,打包编译值后的位置在相应的包下:

3.通过资源绑定器获取到资源文件信息

使用资源绑定器获取资源文件信息,前提:(1)资源文件必须在类路径下,如果不在resource文件夹下,而是在包下,处理方式如下;(2)参数不需要带后缀

package com.lxc.domain; import java.util.ResourceBundle; public class Fanshe {     public static void main(String[] args) {        ResourceBundle resourceBundle = ResourceBundle.getBundle("User");        String username = resourceBundle.getString("username");        System.out.println(username);    }

如果在包文件夹下,路径应该这样写:

package com.lxc.domain; import java.util.ResourceBundle; public class Fanshe {     public static void main(String[] args) {        ResourceBundle resourceBundle = ResourceBundle.getBundle("com/lxc/domain/User");        String username = resourceBundle.getString("username");        System.out.println(username);    }}

到此这篇关于Java中关于文件路径读取问题的分析的文章就介绍到这了,更多相关Java读取文件路径内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

你在无垠的海边第一次听到了自己心跳的声音,

Java中关于文件路径读取问题的分析

相关文章:

你感兴趣的文章:

标签云: