Java读取properties文件

【转】使用J2SE API读取Properties文件的六种方法
 from:http://apps.hi.baidu.com/share/detail/23045976
1。使用java.util.Properties类的load()方法
示例: InputStream in = lnew BufferedInputStream(new FileInputStream(name));
Properties p = new Properties();
p.load(in);

2。使用java.util.ResourceBundle类的getBundle()方法
示例: ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());

3。使用java.util.PropertyResourceBundle类的构造函数
示例: InputStream in = new BufferedInputStream(new FileInputStream(name));
ResourceBundle rb = new PropertyResourceBundle(in);

4。使用class变量的getResourceAsStream()方法
示例: InputStream in = JProperties.class.getResourceAsStream(name);
Properties p = new Properties();
p.load(in);

5。使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法
示例: InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name);
Properties p = new Properties();
p.load(in);

6。使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法
示例: InputStream in = ClassLoader.getSystemResourceAsStream(name);
Properties p = new Properties();
p.load(in);

补充

Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法
示例:InputStream in = context.getResourceAsStream(path);
Properties p = new Properties();
p.load(in);

完整的示例,可以参考附件文件
如何上传文件,谁知道请告诉以下。 只好把source都贴上来了
JProperties.java文件



package com.kindani;

//import javax.servlet.ServletContext;
import java.util.*;
import java.io.InputStream;
import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.FileInputStream;


public class JProperties {

public final static int BY_PROPERTIES = 1;
public final static int BY_RESOURCEBUNDLE = 2;
public final static int BY_PROPERTYRESOURCEBUNDLE = 3;
public final static int BY_CLASS = 4;
public final static int BY_CLASSLOADER = 5;
public final static int BY_SYSTEM_CLASSLOADER = 6;

public final static Properties loadProperties(final String name, final int type) throws IOException {
Properties p = new Properties();
InputStream in = null;
if (type == BY_PROPERTIES) {
in = new BufferedInputStream(new FileInputStream(name));
assert (in != null);
p.load(in);
} else if (type == BY_RESOURCEBUNDLE) {
ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());
assert (rb != null);
p = new ResourceBundleAdapter(rb);
} else if (type == BY_PROPERTYRESOURCEBUNDLE) {
in = new BufferedInputStream(new FileInputStream(name));
assert (in != null);
ResourceBundle rb = new PropertyResourceBundle(in);
p = new ResourceBundleAdapter(rb);
} else if (type == BY_CLASS) {
assert (JProperties.class.equals(new JProperties().getClass()));
in = JProperties.class.getResourceAsStream(name);
assert (in != null);
p.load(in);
// return new JProperties().getClass().getResourceAsStream(name);
} else if (type == BY_CLASSLOADER) {
assert (JProperties.class.getClassLoader().equals(new JProperties().getClass().getClassLoader()));
in = JProperties.class.getClassLoader().getResourceAsStream(name);
assert (in != null);
p.load(in);
// return new JProperties().getClass().getClassLoader().getResourceAsStream(name);
} else if (type == BY_SYSTEM_CLASSLOADER) {
in = ClassLoader.getSystemResourceAsStream(name);
assert (in != null);
p.load(in);
}

if (in != null) {
in.close();
}
return p;

}

// ---------------------------------------------- servlet used


// ---------------------------------------------- support class


public static class ResourceBundleAdapter extends Properties {
public ResourceBundleAdapter(ResourceBundle rb) {
assert (rb instanceof java.util.PropertyResourceBundle);
this.rb = rb;
java.util.Enumeration e = rb.getKeys();
while (e.hasMoreElements()) {
Object o = e.nextElement();
this.put(o, rb.getObject((String) o));
}
}

private ResourceBundle rb = null;

public ResourceBundle getBundle(String baseName) {
return ResourceBundle.getBundle(baseName);
}

public ResourceBundle getBundle(String baseName, Locale locale) {
return ResourceBundle.getBundle(baseName, locale);
}

public ResourceBundle getBundle(String baseName, Locale locale, ClassLoader loader) {
return ResourceBundle.getBundle(baseName, locale, loader);
}

public Enumeration getKeys() {
return rb.getKeys();
}

public Locale getLocale() {
return rb.getLocale();
}

public Object getObject(String key) {
return rb.getObject(key);
}

public String getString(String key) {
return rb.getString(key);
}

public String[] getStringArray(String key) {
return rb.getStringArray(key);
}

protected Object handleGetObject(String key) {
return ((PropertyResourceBundle) rb).handleGetObject(key);
}

}

}

JPropertiesTest.java文件


package com.kindani.test;

import junit.framework.*;
import com.kindani.JProperties;

//import javax.servlet.ServletContext;
import java.util.Properties;

public class JPropertiesTest extends TestCase {
JProperties jProperties;
String key = "helloworld.title";
String value = "Hello World!";

public void testLoadProperties() throws Exception {
String name = null;
Properties p = new Properties();

name = "C:\\IDEAP\\Properties4Methods\\src\\com\\kindani\\test\\LocalStrings.properties";
p = JProperties.loadProperties(name, JProperties.BY_PROPERTIES);
assertEquals(value, p.getProperty(key));

name = "com.kindani.test.LocalStrings";
p = JProperties.loadProperties(name,JProperties.BY_RESOURCEBUNDLE);
assertEquals(value, p.getProperty(key));
assertEquals(value,((JProperties.ResourceBundleAdapter)p).getString(key));

name = "C:\\IDEAP\\Properties4Methods\\src\\com\\kindani\\test\\LocalStrings.properties";
p = JProperties.loadProperties(name, JProperties.BY_PROPERTYRESOURCEBUNDLE);
assertEquals(value, p.getProperty(key));
assertEquals(value,((JProperties.ResourceBundleAdapter)p).getString(key));

name = "\\com\\kindani\\test\\LocalStrings.properties";
p = JProperties.loadProperties(name, JProperties.BY_SYSTEM_CLASSLOADER);
assertEquals(value, p.getProperty(key));

name = "\\com\\kindani\\test\\LocalStrings.properties";
p = JProperties.loadProperties(name, JProperties.BY_CLASSLOADER);
assertEquals(value, p.getProperty(key));

name = "test\\LocalStrings.properties";
p = JProperties.loadProperties(name, JProperties.BY_CLASS);
assertEquals(value, p.getProperty(key));
}


}

properties文件与JPropertiesTest.java文件相同的目录下
LocalStrings.properties文件
# $Id: LocalStrings.properties,v 1.1 2000/08/17 00:57:52 horwat Exp $

# Default localized resources for example servlets
# This locale is en_US

helloworld.title=Hello World!

requestinfo.title=Request Information Example
requestinfo.label.method=Method:
requestinfo.label.requesturi=Request URI:
requestinfo.label.protocol=Protocol:
requestinfo.label.pathinfo=Path Info:
requestinfo.label.remoteaddr=Remote Address:

requestheader.title=Request Header Example

requestparams.title=Request Parameters Example
requestparams.params-in-req=Parameters in this request:
requestparams.no-params=No Parameters, Please enter some
requestparams.firstname=First Name:
requestparams.lastname=Last Name:

cookies.title=Cookies Example
cookies.cookies=Your browser is sending the following cookies:
cookies.no-cookies=Your browser isn't sending any cookies
cookies.make-cookie=Create a cookie to send to your browser
cookies.name=Name:
cookies.value=Value:
cookies.set=You just sent the following cookie to your browser:

sessions.title=Sessions Example
sessions.id=Session ID:
sessions.created=Created:
sessions.lastaccessed=Last Accessed:
sessions.data=The following data is in your session:
sessions.adddata=Add data to your session
sessions.dataname=Name of Session Attribute:
sessions.datavalue=Value of Session Attribute:

------------------------------------------------------------------------------------------------------------------------------------------------------------------

Java对properties配置文件的操作


package com.yorsun;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;


public class PropertiesUnit {
private String filename;

private Properties p;

private FileInputStream in;

private FileOutputStream out;

public PropertiesUnit(String filename) {
this.filename = filename;
File file = new File(filename);
try {
in = new FileInputStream(file);
p = new Properties();
p.load(in);
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.err.println("配置文件config.properties找不到!");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("读取配置文件config.properties错误!");
e.printStackTrace();
}
}

public static String getConfigFile(HttpServlet hs) {
return getConfigFile(hs, "config.properties");
}


private static String getConfigFile(HttpServlet hs, String configFileName) {
String configFile = "";
ServletContext sc = hs.getServletContext();
configFile = sc.getRealPath("/" + configFileName);
if (configFile == null || configFile.equals("")) {
configFile = "/" + configFileName;
}
// TODO Auto-generated method stub
return configFile;
}

public void list() {
p.list(System.out);
}

public String getValue(String itemName) {
return p.getProperty(itemName);
}

public String getValue(String itemName, String defaultValue) {
return p.getProperty(itemName, defaultValue);
}

public void setValue(String itemName, String value) {
p.setProperty(itemName, value);
}

public void saveFile(String filename, String description) throws Exception {
try {
File f = new File(filename);
out = new FileOutputStream(f);
p.store(out, description);
out.close();
} catch (IOException ex) {
throw new Exception("无法保存指定的配置文件:" + filename);
}
}

public void saveFile(String filename) throws Exception{
saveFile(filename,"");
}

public void saveFile() throws Exception{
if(filename.length()==0)
throw new Exception("需指定保存的配置文件名");
saveFile(filename);
}

public void deleteValue(String value){
p.remove(value);
}

public static void main(String args[]){
String file="/eclipse/workspace/NewsTest/WEB-INF/config.properties";
// String file="D:\\eclipse\\workspace\\NewsTest\\WEB-INF\\config.properties";
PropertiesUnit pu=new PropertiesUnit(file);
pu.list();
}

}

--------------------------------------------------------------------------------------------------------------------------------------------------------------------

package com.test.TestClass;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ReadPropertiesFile ...{

public void readPropertiesFile(String fileName) throws FileNotFoundException ...{
String str = "";
Properties prop = new Properties();

InputStream stream = null;

//读取这个类在同一包中的properties文件
//stream = getClass().getClassLoader().getResourceAsStream(fileName);
System.out.println("path:" + getClass().getResource(fileName));


//读取SRC下的的properties文件
String path = getClass().getResource("/").getPath();
stream = new BufferedInputStream(new FileInputStream(new File(path+fileName)));

try ...{
prop.load(stream);
str = prop.getProperty("localname");
System.out.println("localname:" + str);
System.out.println("properties:" + prop);
stream.close();

} catch (IOException e) ...{
// TODO Auto-generated catch block
e.printStackTrace();
}
}


public static void main(String[] args) throws FileNotFoundException ...{
// TODO Auto-generated method stub
new ReadPropertiesFile().readPropertiesFile("config.properties");

}

}

--------------------------------------------------------------------------------------------------------------------------------------

//=================sprin配置文件================================
<bean
id="userService"
class="com.thtf.ezone.ezesb.jmx.admin.service.impl.UserServiceImpl">
<property
name="filePath"
value="config/userInfo.properties" />
</bean>

//=================java文件================================

package com.thtf.ezone.ezesb.jmx.admin.service.impl;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class UserServiceImpl implements UserService {

String filePath = null;

public void setFilePath(String filePath) {
this.filePath = filePath;
}

public static void main(String dd[])throws Exception{

Properties p = new Properties();
FileInputStream ferr=new FileInputStream((getClass().getClassLoader()
.getResource("") + filePath).toString().substring(6));// 用subString(6)去掉:file:/try{
p.load(ferr);
ferr.close();
Set s = p.keySet();
Iterator it = s.iterator();
while(it.hasNext()){
String id = (String)it.next();
String value = p.getProperty(id);
System.out.println(id+":="+value);
}
}catch(Exception e){
e.printStackTrace();
}
}
}

//==============databaseconfing.properties 文件=====================

#----------------------------------
# sql server 2000数据厍连接信息
#----------------------------------
dp.sd.DataBaseTyp=mssql
DataBaseHost=127.0.0.1:1433
DataBase=formpro
UserName=sa
PassWord=01
#----------------------------------
# mysql 数据厍连接信息
#----------------------------------
#DataBaseHost=127.0.0.1:3306
#DataBaseTyp=mysql
#DataBase=snow
#UserName=root
#PassWord=01
//==========================运行结果=======================

PassWord:=01
DataBaseHost:=127.0.0.1:1433
DataBase:=formpro
dp.sd.DataBaseTyp:=mssql
UserName:=sa
 

 

Java中properties文件读取教程 本文还有配套的精品资源,点击获取 简介:在Java应用中,properties文件是用于存储配置信息的常用格式。本篇详细介绍了如何读取properties文件,包括其格式、加载、内容读取、特殊字符处理、默认值设定、内容存储及更新等关键知识点。文章还提供了一些高级使用技巧和最佳实践,帮助开发者高效地处理properties文件,以确保应用程序配置的正确性和安全性。 ... 阅读详情

相关推荐

VizCut 全自动批量视频二次去重处理!支持视频无水印解析下载和批量剪辑,完全免费,使用简单!

可制作和分享剪辑模板,已提供20+种剪辑方案,内置众多扫光蒙版素材。支持二次去重批量处理,完全免费,无广告,且支持视频无水印解析下载,非常强大。如果说我们处理的视频需要进行一样的参数设置的话,就可以把我,1设置的参数设置为模板,后面就可以一键调用。1. 本地CPU处理,可设置线程数,可开启GPU加速,无任何限制,全看机器性能。适用场景:自媒体搬运、短视频二创、批量去重等,完全免费,无广告干扰!3. 20+种参数可调可选,内置很多相关素材。可保存为模板,可复用、可分享、可导入。2. 所有参数的设置,

goodfat的博客 5324

Java读取Properties配置文件的6种方式

Java读取Properties配置文件的6种方式

yirenDM的博客 6527

《通信工程施工与管理》

制作馈线接头必须使用专用的工具,专用工具包括:馈线切割刀、馈线安全刀、小金属丝毛刷、固定尺寸或大号活动扳手、小号扁锉刀、细齿小手锯、接头扩孔器、3M防水胶或防水接头盒;如图所示,详情如表所示。

2302_78710464的博客 1653

读取properties文件的6种方式,建议收藏!

以上就是我们通常在java中读取properties文件的6中方式。

m0_73311735的博客 4550

ANSYS拓扑优化基础实例

唐深51CAE 2018/6/10 拓扑优化在工程设计中,常用于机械结构概念设计和轻量化设计,ANSYS通用有限元分析软件提供了强大的拓扑优化功能,本文将通过一个简单实例进行展示。 一、赵州桥 赵州桥又称安济桥,坐落在河北省赵县洨河上,建于隋朝年间公元595年~605年,由著名匠师李春设计建造,距今已有约1500年的历史,是当今世界上现存最早、保存最完整的古代敞...

TQT_CAE的博客 6027

ZYNQ程序固化实战:从BOOT.bin生成到QSPI/SD卡双启动模式详解

本文详细解析了ZYNQ 7000系列程序固化的完整流程,重点解决了程序断电丢失问题。通过实战演示,从生成BOOT.bin文件到配置QSPI与SD卡双启动模式,逐步指导开发者实现程序在外部存储中的永久驻留,确保产品脱离调试器独立运行。

weixin_29193259的博客 517

Java中读取properties配置文件的八种方式总结

【代码】Java中读取properties配置文件的八种方式总结。

ღ᭄ꦿℒℴѵℯ青城এ⁵²º的博客 6129

华为eNSP与VMware虚拟机联动实战:从零搭建仿真网络环境

本文详细介绍了如何从零开始搭建华为eNSP与VMware虚拟机的联动仿真网络环境。通过环境准备、网络适配器配置、eNSP与VMware网络集成、安全策略与NAT配置等步骤,帮助读者掌握构建企业级网络实验场景的关键技术。这种组合特别适合网络工程师进阶训练和华为认证考试准备,实现低成本、高灵活性的网络仿真实验。

weixin_30415113的博客 504

Java读取properties配置文件的8种方式汇总

Properties 类位于 java.util.Properties中,是Java 语言的处理配置文件所使用的类,其中的xxx.Properties类主要用于集中的持久存储Java的配置文件内容,可以读取后缀是.properties和.cfg的配置文件。Properties类调用setProperty方法将键值对保存到内存中,此时可以通过getProperty方法读取,propertyNames方法进行遍历,但是并没有将键值对持久化到属性文件中,故需要调用store方法持久化键值对到属性文件中。

cuisidong1997的博客 3265

单细胞 | pySCENIC·转录因子分析(二)

接上一篇,pySCENIC分析完之后就可以进行可视化了,个人认为最重要的有三个图:rss点图,rank图,转录因子表达水平热图,3个图结合着看。3.可视化rank图,可以自己改一下plotRSS_oneSet参数让图更好看一点。4. regulon表达水平热图,转录因子表达水平同理,得到的图类似只是输入不一样。2.可视化点图:寻找cluster特异性转录因子。1.loom文件读入R,提取数据。

生信练习生 4286

从零开始:使用英伟达nx开发板部署目标检测算法的全过程

英伟达nx开发板烧录、依赖安装、开发板联网

weixin_51192760的博客 3762

总结java两种常用读取Properties文件方式

java中两种常用的解析properties方法:ClassLoder和ResourceBundle

weixin_43966996的博客 1935

ArcGIS笔记13_利用ArcGIS制作岸线与水深地形数据?建立水动力模型之前的数据收集与处理?

在利用MIKE建立水动力模型之前,需要收集、处理和制作诸多数据和资料,主要有岸线数据、水深地形数据、开边界潮位驱动数据、风场数据、潮位和海流观测资料和站点潮汐调和常数资料等。本篇主要介绍这些资料的获取与处理。

晏长街的博客 5948

Java读取properties配置文件工具包

与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。java中的properties文件是一种配置文件,主要用于表达配置信息,文件类型为*.properties,格式为文本文件,文件的内容是格式是 "键=值"的格式,在properties文件中,可以用"#"来作注释,properties文件在Java编程中用到的地方很多,操作很方便。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。他通过调用基类的put方法来设置 键 - 值对。

Meryoufdd的博客 3748

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

java读取properties文件_Java读取Properties文件的六种方法

Java读取Properties文件有以下六种方法:1。使用java.util.Properties类的load()方法StringfileName="E:/system.properties";InputStreamin=newBufferedInputStream(newFileInputStream(fileName));Propertiesp=newProperties...

weixin_33327380的博客 4810

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

java怎么读取properties文件、修改properties文件和封装properties

什么是Properties文件,Properties文件和XML一样是java中经常使用到的一种配置文件,读取和使用起来比较方便,并且可读性好。我们在编写代码的过程中为了将代码提高可参数化经常会将一些配置属性存放在我们的配置文件中,例如JDBC的URL、用户名、密码等甚至一些文件路径或者是一些常用的参数。这样我们当数据库发生改变的时候就不需要改原有的代码了。 Properties文件的特点就是Ke...

柳轻声的博客 2694

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

Java读取Properties文件的六种方法

使用J2SE API读取Properties文件的六种方法1。使用java.util.Properties类的load()方法示例: InputStream in = lnew BufferedInputStream(new FileInputStream(name));Properties p = new Properties();p.load(in);2。使用java.util.Resou...

小宝 3361

Java中读取properties文件

JAVA中读取properties文件 Java读取properties 配置文件的几种方式 介绍几种读取方式: db.properties文件 driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/jdbcdemo?serverTimezone=GMT%2B8 user=root user=root 1...

qq_37586652的博客 921

Java 读取 Properties 文件

案例一 主要使用了spring-core-4.1.4.RELEASE-sources.jar 这个jar包里的 PropertiesLoaderUtils.loadProperties 方法。不说了,直接上代码: package cn.lyj.util; import java.util.HashMap; import java.util.Map; import java.u...

小半的博客 2262

如何读取Java中properties文件的数据

如何读取Java中properties文件的数据 Properties类 想要读取properties文件的数据,首先需要知道Properties类(java.util.Properties),该类是Hashtable的一个子类;此外,从源代码的前几行注释可知,该properties类代表一个持久型属性集,该属性可以被保存到一个流中(inputStream,FileInputStream …),或者是从流中加载,属性列表中的每个键及其对应的值都是一个字符串: /** * The {@code Proper

qq_40898875的博客 1939

java读取properties文件_java读取properties文件的几种方法

一、项目中经常会需要读取配置文件(properties文件),因此读取方法总结如下:1、通过java.util.Properties读取1 Properties p=newProperties();2 //p需要InputStream对象进行读取文件,而获取InputStream有多种方法:3 //1、通过绝对路径:InputStream is=new FileInputStream(filePa...

weixin_33249310的博客 3968

JAVA按顺序读取properties文件

这里写自定义目录标题欢迎使用Markdown编辑器新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML 图表FLowchart流程图导出与导入导出导入 加粗样式 欢...

csdnwcy的博客 1463

Java读取properties配置文件工具类

Java读取properties配置文件的方式 一.背景 Java读取 properties 配置文件的方式,主要是通过 getProperty() 方法。config.properties 文件中有诸如 config.a = xxx 这样的存储形式,下面代码是读取 properties 配置文件中参数数据到 String 类型变量中。 二.代码 // 新建一个拥有 config.properti...

abcnull 的博客 2017
上一篇: 使用反射获得泛型的实际参数
下一篇: Java中的static final与final,空白final的相关知识
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值