java 读取 properties文件的各种方法

Java工程中读取resources目录下properties文件的几种方法 既已说到spring cloud alibaba,那对于整个微服务架构,如果想要进一步地向上提升自己,到底应该掌握哪些核心技能呢?就个人而言,对于整个微服务架构,像RPC、Dubbo、Spring Boot、Spring Cloud Alibaba、Docker、kubernetes、Spring Cloud Netflix、Service Mesh等这些都是最最核心的知识,架构师必经之路!下图,是自绘的微服务架构路线体系大纲,如果有还不知道自己该掌握些啥技术的朋友,可根据小编手绘的大纲进行一个参考。 阅读详情

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);

示例

 

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

淘宝链接跳转微信全攻略:自建合规中转页实现私域引流 在跨平台运营中,链接跳转是连接不同生态、实现流量引导的关键技术。其核心原理是通过服务器端或前端逻辑,将用户从一个平台的链接安全引导至目标页面,同时规避平台间的访问限制。这项技术的核心价值在于打破数据孤岛,实现跨平台用户沉淀与精细化运营,广泛应用于电商引流、私域流量构建和跨平台营销等场景。本文聚焦于**淘宝短链**与**企业微信**之间的跳转难题,提供了一套基于自建中转页面的完整工程解决方案,手把手教你如何通过合规的技术手段,将淘宝流量高效、安全地引导至微信生态,并实现数据追踪与客户分流。 阅读详情

相关推荐

SPL06气压温度传感器SPI驱动与补偿算法详解

气压传感器与温度传感器是嵌入式环境感知系统的核心组件,其测量精度高度依赖于MEMS芯片的校准参数与非线性补偿机制。SPL06作为集成式高精度数字传感器,采用24位Σ-Δ ADC与片内补偿引擎,需结合唯一出厂校准系数(即‘芯片指纹’)进行多阶数学修正,才能将原始ADC值转化为符合计量要求的帕斯卡(Pa)与摄氏度(℃)物理量。该过程涵盖SPI通信协议解析、寄存器时序控制、大端数据拼接、二进制补码处理及浮点/定点混合运算等典型嵌入式工程实践。广泛应用于无人机高度计、智能穿戴海拔监测与IoT气象终端中。

weixin_34640289的博客 143

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

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

yirenDM的博客 6527

保姆级教程:在Ubuntu 22.04上搞定PX4 V1.14 + ROS2 Humble的HITL仿真(避坑实录)

本文提供在Ubuntu 22.04上配置PX4 V1.14与ROS2 Humble的HITL仿真环境的详细教程,涵盖环境准备、固件编译、QGroundControl配置、ROS2通信设置及联调测试。特别针对版本兼容性、Gazebo插件构建和MicroDDS配置等常见问题提供避坑指南,帮助开发者高效搭建无人机仿真系统。

weixin_30836759的博客 1003

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

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

m0_73311735的博客 4550

PTA 7-8 暴力小学(二年级篇)-求出4个数字 (10分)java

PTA 7-8 暴力小学(二年级篇)-求出4个数字 (10分)java 小博是新城小学二年级学生,这孩子人很老实,数学、语文成绩都是中等。不过一旦坐在电脑前,写起代码来,则有些霸气侧漏,尤其擅长各种暴力方法。本题就是数学莫老师的题目之一,请你和小博一起暴力求解吧。 输入格式: 第一行给出这个和N(图中例子的和N为2000)。 输出格式: 第一行输出所有解的数目K,随后K行按照DCBA 4位数字从...

qryzhfj的博客 2188

VTK基础教程(1)- vtkPolyData 介绍

目录 VTK的编译与环境搭建 VTK一般渲染流程 VTK数据类型-vtkPolyData 使用vtk自带的多边形数据 使用自己创建的数据 添加顶点颜色 添加面颜色 VTK的编译与环境搭建 这部分目前已经有了大佬做了成熟的傻瓜式配置,大家可以参考这篇文章:VTK+VS2019(或其他版本均可) 傻瓜式一站式 配置_Nancy_fairy的博客-优快云博客_vs2019 vtk VTK一般渲染流程 这部分的介绍也很多,大家可以参考这篇文章:VTK笔记-了解VTK_黑山老妖的博客.

qq_35769071的博客 9054

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

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

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

详解从无人机倾斜实景三维建模→模型修复→成果网络发布展示分享全流程

1、倾斜实景三维建模软件:CC(Smart3D)软件2、实景三维模型网页在线发布展示、分享平台:图新地球网页端(Wish3D·Earth平台)图新地球网页端(Wish3D·Earth平台)是基于 WebGL技术研发的国产实景三维模型Web端发布展示平台,可实现TB级倾斜实景三维数据快速加载,支持多种格式的三维模型,如OSGB实景模型、OBJ人工模型、SKP人工模型、RVT格式BIM模型等,同时支持模型单体化、三维模型测量分析、水面特效、日照分析等特殊效果呈现,此外也可以根据您的需要进行本地化部署级功能定制。

GISWorld3D的博客 4376

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

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

cuisidong1997的博客 3265

【UE4】Hierarchical Instanced Static Mesh——一种速度优于Spawn的实例化物体组件

最近需要在场景中实例出很多个相同的模型,位置也很有规律,并且要对它的位置信息进行更新。 但是一个个拖进去实在太麻烦,就发现了Spawn Actor这个蓝图方法,可以实例一个蓝图类在场景中。 但是由于数量较大,实例化的速度太慢,这时发现了一个神奇的组件——Hierarchical Instanced Static Mesh。 新建一个蓝图类,添加该组件,在细节里添加你要实例化的模型对象。 ...

ColorGalaxy 1万+

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

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

weixin_43966996的博客 1934

ABAP SQL Hierarchy 全景参考,组织树、分类树与递归查询在数据库层的优雅落地

ABAP SQL中的hierarchy语法为树形数据结构处理提供了高效方案。S/4HANA系统中常见的成本中心、利润中心、物料分类等树形结构,传统开发需通过递归和嵌套循环处理,而ABAP SQL hierarchies通过将层级遍历能力下沉到SQL层,借助SAP HANA的层级函数支持,实现了更高效的查询。 该功能要求ABAP 7.51+版本,支持两种实现方式:CDS hierarchy用于创建可复用的稳定层级模型,适合业务核心数据;ABAP SQL HIERARCHY generator则适用于临时性层级

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 313

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

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

weixin_33327380的博客 4810

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

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

小宝 3360

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

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

jre9下载 jdk9

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

java中读取properties文件的方法

简单说一下读取properties文件的方法 //通过类加载器进行获取properties文件流 InputStream in = 类名.class.getClassLoader().getResourceAsStream("jdbc.properties"); //创建Properties类 Properties properties = new Properties() //加载流文件 properties.load(in); //获取properties文件内容 String content=

✈ 正在努力 の 寒江(StudiousTiger) ✌ 呐 ✈ 237

java读取.properties配置文件的几种方法

读取.properties配置文件在实际的开发中使用的很多,总结了一下,有以下几种方法(仅仅是我知道的): 一、通过jdk提供的java.util.Properties类。 此类继承自java.util.HashTable,即实现了Map接口,所以,可使用相应的方法来操作属性文件,但不建议使用像put、putAll这两个方法,因为put方法不仅允许存入String类型的value,还可以存入O

痴人说梦 7万+

java 读取多个properties_java读取properties文件方法

简介我们在做一些Java应用开发的时候,会将很多环境特定的变量定义到一个配置文件中。比较常见的定义文件有xml, properties,甚至txt等格式的。在Java里有一个类似于标准配置格式的文件,就是.properties类型的文件。它主要用来存储一些名值对的内容,里面的内容都存成如propertyname=propertyvalue这种样式。读取properties文件的方法有很多种,网上也...

weixin_42165980的博客 647

java读取properties文件方法

InputStream inputStream = ClassLoader.getSystemResourceAsStream("C:/Users/520/Desktop/function.properties"); //InputStream inputStream=ClassLoader.getSystemResourceAsStream("i18n/function.properties"); Properties properties = new Properties(); .

wangpeng1201的博客 200
上一篇: poi 和jxl的性能比较,借鉴别人的,本人没有测试过,不过感觉自己可以接收这种解释
下一篇: 在tomcat中配置jndi
java_min
博客等级 码龄18年 61粉丝 161原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值