栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java读取资源文件的方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java读取资源文件的方法

如何获得当前文件路径

(1).Test.class.getResource("")

得到的是当前类FileTest.class文件的URI目录。不包括自己

(2).Test.class.getResource("/")

得到的是当前的classpath的绝对URI路径。

(3).Thread.currentThread().getContextClassLoader().getResource("")

得到的也是当前ClassPath的绝对URI路径。

(4).Test.class.getClassLoader().getResource("")

得到的也是当前ClassPath的绝对URI路径。

(5).ClassLoader.getSystemResource("")

得到的也是当前ClassPath的绝对URI路径。

(6) new File("").getAbsolutePath()也可用。

尽量不要使用相对于System.getProperty(“user.dir”)当前用户目录的相对路径,后面可以看出得出结果五花八门。

Web服务器

(1).如何读文件

使用ServletContext.getResourceAsStream()就可以

(2).获得文件真实路径

String file_real_path=ServletContext.getRealPath(“mypath/filename”);

不建议使用request.getRealPath("/");

使用java.util.Properties类的load()方法:

使用绝对路径

URL resource = Resoures_properties.class.getResource("");
        String path = resource.getPath();

        InputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(path+ "properties/jdbc.properties"));
        Properties properties = new Properties();
        properties.load(bufferedInputStream);
        String url = properties.getProperty("url");
        System.out.println(url);

使用java.util.Resourcebundle类的getbundle()方法 :

文件存放在工程的resource目录下,或者lib目录下、或者可以放在src目录其他包下,也可以不放…用来读取项目中后缀为properties的配置文件

ResourceBundle resource = ResourceBundle.getBundle("jdbc");  
String className = resource.getString("database.driver");

使用java.util.PropertyResourceBundle类的getBundle函数:

properties 文件存放在工程的resource目录下或 放在src下,可以放在src目录其他包下,也可以不放

PropertyResourceBundle propertyResourceBundle = (PropertyResourceBundle) PropertyResourceBundle.getBundle("properties/jdbc");
        String url = propertyResourceBundle.getString("url");
        System.out.println(url);

使用class变量的getResourceAsStream()方法:

包点类名下的。或存放在工程的resource目录下,这时要从classpath的根访问
如果找不到带有该名称的资源,则返回 null

InputStream  in=类名.class.getResourceAsStream("properties/jdbc.properties"); 
Properties p = new Properties();
p.load(in);
System.out.println(p.getProperty("database.url")); 
使用class.getclassloader()所得到的java.lang.classloader的getResourceAsStream()方法:

properties 文件 存放在工程的resource目录下或放在src下面,否则找不到啊,可以放在src目录其他包下,也可以不放

InputStream in = 类名.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties p = new Properties() ;
p.load(in); 
System.out.println(p.getProperty("database.pass"));
使用java.lang.classloader类的getSystemResourceAsStream()静态方法

properties 文件 存放在工程的resource目录下或放在src下,可以放在src目录其他包下,也可以不放

InputStream in = ClassLoader.getSystemResourceAsStream("properties/jdbc.properties"); 
Properties p = new Properties() ;
p.load(in) ;
System.out.println(p.getProperty("database.user"));
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/361572.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号