Java读取Properties文件的六种方法

西门子TP900精智系列触摸屏和三菱Q系列PLC以太网通信的组态步骤 阅读详情

Java读取Properties文件的六种方法

Java读取Properties文件的六种方法

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.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

为了您的安全,请只打开来源可靠的网址

打开网站    取消

来自: http://hi.baidu.com/hgd0324/blog/item/11f3933f19f4eafd828b1391.html

YOLOv11 改进入门篇 | 轻量级涨点技巧:GhostConv 替代普通卷积的实战指南 摘要: 本文介绍如何通过GhostConv改进YOLOv11,实现轻量化涨点。YOLOv11深度增加导致参数量、延迟和内存占用上升,GhostConv通过“本征特征+线性变换”策略,在精度几乎无损的情况下降低30%-50%计算量。文章详细解析GhostConv原理,对比普通卷积的参数量和FLOPs优势,并提供完整的代码级改造流程,包括模块实现、注册及网络配置。实验表明,该方法有效提升边缘端推理效率,适用于移动端等资源受限场景。 阅读详情

相关推荐

GPS卫星轨道的理论和计算笔记分享

广义相对论预测,对比在时空弯曲度较大的地面上的原子钟,运行于时空弯曲度较小的卫星原子钟在地面上看起来更快,每天快约45us;反过来,当电压施加在晶体上时,晶体形状会扭曲(比如说伸长),而当晶体被施加上反向电压后,它将做相反的变形运动(比如缩短)。X轴:指向参考子午面与地球赤道的一个交点;从北黄极上方观察,地球北极在空间的运动轨迹是一个近似于以北黄极为中心的顺时针方向旋转的圆周,圆周半径等于。从上万年周期看,地球北极绕北黄极做大圆周运动,而从几年的短期来看,北极又在某一点处做局部的小幅椭圆运动。

m0_57139844的博客 2003

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

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

yirenDM的博客 6527

汽车诊断服务(UDS——0x11服务解析)

ECU复位服务(0x11)详解:该服务支持硬件/钥匙开关/软件三种复位类型(0x01-0x03),复位前需发送肯定响应。请求格式为11+子功能,响应含51+子功能。典型应用需配合安全访问流程,测试时需监控CAN总线通信及DTC状态。复位后ECU将返回默认会话,期间不处理任何诊断请求。服务在编程会话且安全解锁后执行,硬复位会初始化存储数据。

从事汽车行业 979

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

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

m0_73311735的博客 4550

嵌入式设备的switch 以及PHY 芯片调试和选型 (1)

越来越的设备需要多网口的需求,于是需求搭配一个交换机实现网口的扩展。但是很多软件或是硬件工程师在实际选型和应用中经常会遇到一些问题。这里总结一下,避免大家采坑。 几个概念: MAC(介质访问控制),可以理解成数据链路层即可 PHY(物理性),简单理解层转成物理层的连接组件即可 控制接口(MDC/DMIO,I2C,...

睿峰的博客 1万+

TMC5130/TMC5160步进电机驱动芯片深度解析与工程实践

步进电机驱动芯片是精密运动控制系统的物理执行核心,其性能直接决定定位精度、运行噪声与系统鲁棒性。基于电流闭环控制与电压前馈调制的混合驱动原理,现代智能驱动芯片如TMC51X0系列实现了微步插补、堵转检测和片上运动规划等关键技术突破。这类芯片通过SPI寄存器级配置实现StealthChop静音驱动与SpreadCycle高动态响应模式的无缝切换,在3D打印、CNC、机器人关节等场景中显著提升能效比与控制带宽。本文围绕TMC5130与TMC5160的硬件架构差异、寄存器操作时序、驱动模式物理机制及FreeRTO

weixin_35797963的博客 409

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

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

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

华为OD机试真题2025双机位A卷 Java&Go 实现【采购订单】

在一个采购系统中,采购申请(PR)需要经过审批后才能生成采购订单(PO)。每个PR包含商品的单价(假设相同商品的单价一定是一样的)及数量信息。系统要求对商品进行分类处理:单价高于100元的商品需要单独处理,单价低于或等于100元的相同商品可以合并到同一采购订单PO中。针对单价低于100的小额订单,如果量大可以打折购买。

MISAYAONE的博客 1257

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

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

weixin_43966996的博客 1934

Python入门实战:Python生物信息学编程基础

本文旨在为生物学背景的研究人员和对生物信息学感兴趣的程序员提供一个全面的Python生物信息学编程入门指南。我们将从Python基础知识开始,逐步深入到生物信息学特定的工具和技术,最终达到能够独立开发生物信息学分析程序的水平。Python编程基础生物信息学常用数据结构和算法DNA和蛋白质序列分析基因组数据处理生物信息学数据可视化Biopython库的使用实际项目案例背景介绍:概述文章目的、范围和预期读者核心概念与联系:介绍Python和生物信息学的基本概念。

AI架构师小马 1510

Modbus RTU/TCP协议栈手写实现:主从站设计、功能码、CRC、异常响应

本文从协议栈架构、帧结构、功能码、CRC校验、异常响应、主从站设计等多个维度,完整阐述了Modbus RTU/TCP协议栈的手写实现方案。帧间隔机制是RTU的核心,T3.5超时检测决定了帧边界识别CRC16查表法以512字节ROM换取8倍性能提升,适合嵌入式功能码路由表实现可扩展的代码架构,便于新增功能异常响应机制保障协议健壮性,每个错误都有明确反馈Modbus TCP在RTU基础上增加MBAP头,实现以太网扩展多核RTOS环境下的并发访问与线程安全RS-485总线的电气隔离与浪涌保护。

从事移动开发八年,csdn博客专家,阿里云特邀专家,华为云云享专家,高级网络信息安全工程师,大数据工程师(高级),python技术开发(高级),HarmonyOS 应用开发者高级认证,现在某学校任教。 1万+

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

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

cuisidong1997的博客 3265

组态王与DLT645-2007电能表通讯调试总结

组态王与电力协议DLT 645-2007调试总结 DLT 645-2007是多功能电能表通信协议,该标准由中国电力企业联合会2006年提出,该协议为主-从结构的半双工通信方式。手持单元或其它数据终端为主站,多功能电能表为从站。每个多功能电能表均有各自的地址编码。通信链路的建立与解除均由主站发出的信息帧来控制。帧是传送信息的基本单元,每帧由帧起始符、从站地址域、控制码、数据域长度、数据域、帧信息纵向校验码及帧结束符7个域组成,每部分由若干字节组成,帧格式如图1所示。 1.确定设备地址 地址域由 6 个字节构

逍遥子的博客 1万+

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

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

weixin_33327380的博客 4810

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

JAVA读取Properties文件的六种方法

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

廉颇老矣,尚能饭否? (jdk+算法+spring+netty+大数据+OS+Architect) 190

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

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.ut

大树下那片阴凉 1247

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

上一篇: Java读取xml四种方法
下一篇: hibernate抓取效率问题
阳小良
博客等级 码龄17年 54粉丝 155原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值