首页 / JAVA / java中读取资源文件的方法
java中读取资源文件的方法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java中读取资源文件的方法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2454字,纯文字阅读大概需要4分钟。
内容图文
展开全部1.使用java.util.Properties类的load()方法
示例:
//文件在项目下。不是在包下!!
InputStream in = new BufferedInputStream(new FileInputStream("demo.properties")) ;
Properties p = new Properties();
p.load(in) ;
String className2 = p.getProperty("database.driver");
String url = p.getProperty("database.url");
String user = p.getProperty("database.user");
String password = p.getProperty("database.pass");
2. 使用java.util.Resourcebundle类的getbundle()方法
//前面没有“/”代表当前类的目录
示例:
//文件和类在同一个包下,注意它的文件名和后缀!!是调换的,
ResourceBundle resource = ResourceBundle.getBundle("properties.jdbc");
String className = resource.getString("database.driver");
String url = resource.getString("database.url");
String user = resource.getString("database.user");
String password = resource.getString("database.pass");
3.使用java.util.PropertyResourceBundle类的构造函数
示例:
// 文件在项目下 或者 src/demo.properties
// 在 src/demo.properties 写成 new FileInputStream("src/demo.properties")
InputStream in = new BufferedInputStream(new FileInputStream("demo.properties"));
ResourceBundle rb = new PropertyResourceBundle(in) ;
String className4 = rb.getString("database.url");
4.使用class变量的getresourceasstream()方法
示例:
InputStream in =Properties.class.getResourceAsStream("/properties/jdbc.properties");
// 包点类名下的。
// 如果找不到带有该名称的资源,则返回 null
Properties p = new Properties();
p.load(in);
System.out.println(p.getProperty("database.url"));
5.使用class.getclassloader()所得到的java.lang.classloader的getresourceasstream()方法
// properties 文件 要放在src下面,否则找不到啊
示例:
InputStream in = 类名.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties p = new Properties() ;
p.load(in);
System.out.println(p.getProperty("database.pass"));
6.使用java.lang.classloader类的getsystemresourceasstream()静态方法
示例:
// 同包名下
InputStream in = ClassLoader.getSystemResourceAsStream("properties/jdbc.properties");
Properties p = new Properties() ;
p.load(in) ;
System.out.println(p.getProperty("database.user"));
总结:如果是 在WEB上读取properties文件,写成下面这种。上面写的那些只在 JavaSE 中
String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
System.out.println(path);
InputStream in = new FileInputStream(new File(path+File.separator+"mysql.properties"));
Properties prop = new Properties();
内容总结
以上是互联网集市为您收集整理的java中读取资源文件的方法全部内容,希望文章能够帮你解决java中读取资源文件的方法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。