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"));
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值