java的property

本文介绍了Java中properties文件的基本概念、JDK内置的Properties类及其主要方法,包括读取、写入、获取值、清除等操作,并通过代码实例展示了如何在Java程序中使用properties文件进行配置信息的管理。
[size=large]
java的property配置文件的用法(转)


各种语言都有自己所支持的配置文件类型。比如 Python ,他支持 .ini 文件。因为他内部有一个 ConfigParser 类来支持 .ini 文件的读写,根据该类提供的方法程序员可以自由的来操作 .ini 文件。而在 Java 中, Java 支持的是 .properties 文件的读写。 JDK 内置的 Java.util.Properties 类为我们操作 .properties 文件提供了便利。

# 以下为服务器、数据库信息

databaseName = mydb
dbUserName = root
dbPassword = root

dbTable = mytable

ip = 192.168.0.9

二. JDK 中的 Properties 类 Properties 类存在于胞 Java.util 中,该类继承自 Hashtable ,它提供了几个主要的方法:
1. getProperty ( String key) , 用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。

3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。

5. clear () ,清除所有装载的 键 - 值对。该方法在基类中提供。

三.代码实例

import Java.io.FileInputStream;
import Java.io.FileNotFoundException;
import Java.io.FileOutputStream;
import Java.io.IOException;
import Java.util.Properties;
/** *//**
* 读取properties文件
* @author Qutr
*
*/
public class Configuration
...{
private Properties propertie;
private FileInputStream inputFile;
private FileOutputStream outputFile;

/** *//**
* 初始化Configuration类
*/
public Configuration()
...{
propertie = new Properties();
}

/** *//**
* 初始化Configuration类
* @param filePath 要读取的配置文件的路径+名称
*/
public Configuration(String filePath)
...{
propertie = new Properties();
try ...{
inputFile = new FileInputStream(filePath);
propertie.load(inputFile);
inputFile.close();
} catch (FileNotFoundException ex) ...{
System.out.println("读取属性文件--->失败!- 原因:文件路径错误或者文件不存在");
ex.printStackTrace();
} catch (IOException ex) ...{
System.out.println("装载文件--->失败!");
ex.printStackTrace();
}
}//end ReadConfigInfo(...)

/** *//**
* 重载函数,得到key的值
* @param key 取得其值的键
* @return key的值
*/
public String getValue(String key)
...{
if(propertie.containsKey(key))...{
String value = propertie.getProperty(key);//得到某一属性的值
return value;
}
else
return "";
}//end getValue(...)

/** *//**
* 重载函数,得到key的值
* @param fileName properties文件的路径+文件名
* @param key 取得其值的键
* @return key的值
*/
public String getValue(String fileName, String key)
...{
try ...{
String value = "";
inputFile = new FileInputStream(fileName);
propertie.load(inputFile);
inputFile.close();
if(propertie.containsKey(key))...{
value = propertie.getProperty(key);
return value;
}else
return value;
} catch (FileNotFoundException e) ...{
e.printStackTrace();
return "";
} catch (IOException e) ...{
e.printStackTrace();
return "";
} catch (Exception ex) ...{
ex.printStackTrace();
return "";
}
}//end getValue(...)

/** *//**
* 清除properties文件中所有的key和其值
*/
public void clear()
...{
propertie.clear();
}//end clear();

/** *//**
* 改变或添加一个key的值,当key存在于properties文件中时该key的值被value所代替,
* 当key不存在时,该key的值是value
* @param key 要存入的键
* @param value 要存入的值
*/
public void setValue(String key, String value)
...{
propertie.setProperty(key, value);
}//end setValue(...)

/** *//**
* 将更改后的文件数据存入指定的文件中,该文件可以事先不存在。
* @param fileName 文件路径+文件名称
* @param description 对该文件的描述
*/
public void saveFile(String fileName, String description)
...{
try ...{
outputFile = new FileOutputStream(fileName);
propertie.store(outputFile, description);
outputFile.close();
} catch (FileNotFoundException e) ...{
e.printStackTrace();
} catch (IOException ioe)...{
ioe.printStackTrace();
}
}//end saveFile(...)

public static void main(String[] args)
...{
Configuration rc = new Configuration(".\config\test.properties");//相对路径

String ip = rc.getValue("ipp");//以下读取properties文件的值
String host = rc.getValue("host");
String tab = rc.getValue("tab");

System.out.println("ip = " + ip + "ip-test leng = " + "ip-test".length());//以下输出properties读出的值
System.out.println("ip's length = " + ip.length());
System.out.println("host = " + host);
System.out.println("tab = " + tab);
Configuration cf = new Configuration();
String ipp = cf.getValue(".\config\test.properties", "ip");
System.out.println("ipp = " + ipp);
// cf.clear();
cf.setValue("min", "999");
cf.setValue("max", "1000");
cf.saveFile(".\config\save.perperties", "test");

// Configuration saveCf = new Configuration();
// saveCf.setValue("min", "10");
// saveCf.setValue("max", "1000");
// saveCf.saveFile(".\config\save.perperties");

}//end main()

}//end class ReadConfigInfo

Java properties文件的操作
----------------------------------------------------
Java中的properties文件是一种配置文件,主要用于表达配置信息,文件类型为*.properties,格式为文本文件,文件的内容是格式是"键=值"的格式,在properties文件中,可以用"#"来作注释,properties文件在Java编程中用到的地方很多,操作很方便。下面是一个操作Java properties文件的例子,给出了操作方法和properties文件。从中可以看到如何读取properties文件,并应用读取出来的值,是学习操作properties文件的好例子。

IcisReport.properties
------------------------------------------------------
#################################
# 工商报表应用IcisReport的配置文件 #
# 作者:雷智民 #
# 日期:2006年11月21日 #
#################################
#
# 说明:业务系统TopIcis和报表系统IcisReport是分离的
# 可分开部署到不同的服务器上,也可以部署到同一个服务
# 器上;IcisReprot作为独立的web应用程序可以使用任何
# 的Servlet容器或者J2EE服务器部署并单独运行,也可以
# 通过业务系统的接口调用作为业务系统的一个库来应用.
#
# IcisReport的ip
IcisReport.server.ip=192.168.3.143
# IcisReport的端口
IcisReport.server.port=8080
# IcisReport的上下文路径
IcisReport.contextPath=/IcisReport

二、操作properties文件的Java方法

/** *//**
* @return 获取IcisReport报表应用的URL
*/
private String getIcisReportURL() ...{
String icisReportURL = ""; // IcisReport报表应用的URL
String icisReportServerIP = ""; // IcisReport服务器的IP
String icisReportServerPort = ""; // IcisReport服务器的服务端口
String icisReportContextPath = ""; // IcisReport应用的ContextPath
Properties prop = new Properties();
InputStream in;
try ...{
in = getClass().getResourceAsStream("/IcisReport.properties");
prop.load(in);
Set keyValue = prop.keySet();
for (Iterator it = keyValue.iterator(); it.hasNext();) ...{
String key = (String) it.next();
if (key.equals("IcisReport.server.ip")) ...{
icisReportServerIP = (String) prop.get(key);
} else if (key.equals("IcisReport.server.port")) ...{
icisReportServerPort = (String) prop.get(key);
} else if (key.equals("IcisReport.contextPath")) ...{
icisReportContextPath = (String) prop.get(key);
}
}
} catch (Exception e) ...{
log.error("IO读取出错,找不到IcisReport.properties!");
}
if (icisReportServerIP.trim().equals("")) ...{
log
.error("请检查配置文件IcisReport.properties中的IcisReport.server.ip项的值是否正确!");
}
if (icisReportServerPort.trim().equals("")) ...{
log
.error("请检查配置文件IcisReport.properties中的IcisReport.server.port项的值是否正确!");
}
if (icisReportServerPort.trim().equals("")) ...{
log
.error("请检查配置文件IcisReport.properties中的IcisReport.server.port项的值是否正确!");
}
icisReportURL = "http://" + icisReportServerIP.trim() + ":"
+ icisReportServerPort.trim() + icisReportContextPath.trim();
log.info("获取的icisReportURL=" + icisReportURL);
return icisReportURL;
}
总结:Java的properties文件需要放到classpath下面,这样程序才能读取到,有关classpath实际上就是Java类或者库的存放路径,在Java工程中,properties放到class文件一块。在web应用中,最简单的方法是放到web应用的WEB-INF\classes目录下即可,也可以放在其他文件夹下面,这时候需要在设置classpath环境变量的时候,将这个文件夹路径加到classpath变量中,这样也也可以读取到。在此,你需要对classpath有个深刻理解,classpath绝非系统中刻意设定的那个系统环境变量,WEB-INF\classes其实也是,Java工程的class文件目录也是。[/size]
<think>好的,我现在需要回答用户关于Java中的property属性及其相关问题和解决方案的疑问。首先,我需要明确用户的问题范围,他们可能想了解property的基本概念、使用方法、常见问题以及解决方法。 首先,回顾Java中的property属性。PropertyJava中通常指的是通过getter和setter方法访问的类成员变量,遵循JavaBean的命名规范。此外,还有`java.util.Properties`类,用于处理配置文件,比如.properties文件。这两者都是用户可能提到的内容,需要区分清楚。 用户提到“property usage or issues”,可能涉及配置文件的读取、存储问题,或者属性在类中的封装和使用问题。另外,结合用户提供的引用内容,他们可能遇到了时间日期不正确的问题,比如在Docker容器中时区设置不正确导致的日志时间错误,这可能与系统属性或环境变量有关。 接下来,我需要组织回答的结构。首先解释property的基本概念,包括JavaBean属性和Properties文件的使用。然后,列举常见的问题,比如配置文件加载失败、编码问题、时区问题等,并提供相应的解决方案。同时,结合用户提供的引用,特别是引用[2]中的时间问题,需要详细说明如何通过设置时区系统属性来解决。 还需要注意用户提到的系统级指令,比如使用正确的中文回答,生成相关问题,正确使用LaTeX格式。例如,在提到系统属性时,使用$...$包裹代码,如`user.timezone`应写成`$user.timezone$`。同时,独立公式可能需要使用$$...$$,但这里可能不太涉及数学公式,所以重点放在代码和属性名称的正确格式上。 然后,检查是否有遗漏点。比如,Properties文件的安全性问题,比如敏感信息泄露,或者属性覆盖的问题。此外,Java 8之后的`java.util.Properties`是否有更新需要注意的地方?可能不需要,但可以提及使用try-with-resources来自动关闭流,提高代码健壮性。 生成的相关问题需要围绕property的不同方面,比如配置管理、时区问题、加密处理、国际化和与Spring集成等。确保问题覆盖用户可能进一步询问的方向。 最后,确保引用正确。用户提供的引用[^2]涉及到Docker中的时间问题,解决方案中提到设置时区,这可以通过Java系统属性`$user.timezone$`来实现,所以在回答中要引用这一点,并自然添加引用标识。 总结回答结构: 1. Java Property的定义和两种类型 2. 常见使用方式(JavaBean属性、Properties文件) 3. 常见问题及解决方案(包括时区问题引用) 4. 高级用法和安全性 5. 相关问题列表 确保每个部分简明扼要,符合用户要求的清晰结构,并引用相关部分。</think>### Java Property属性详解与常见问题解决 #### 一、Property属性的定义与类型 1. **JavaBean属性** 通过`getXxx()`和`setXxx()`方法操作的私有字段,例如: ```java public class User { private String name; // 字段 public String getName() { return name; } // getter public void setName(String name) { this.name = name; } // setter } ``` 这种属性遵循**封装原则**,用于控制对象状态的访问[^1]。 2. **配置文件属性** 使用`$java.util.Properties$`类管理键值对,常用于读取`.properties`文件: ```properties # app.properties db.url=jdbc:mysql://localhost:3306/test db.user=root ``` --- #### 二、Properties文件的使用方法 1. **加载与读取** ```java try (InputStream input = new FileInputStream("app.properties")) { Properties prop = new Properties(); prop.load(input); // 加载文件 String dbUrl = prop.getProperty("db.url"); // 读取值 } catch (IOException e) { e.printStackTrace(); } ``` 2. **动态修改属性** ```java prop.setProperty("db.user", "admin"); // 修改属性 prop.store(new FileOutputStream("app.properties"), "Updated user"); // 保存 ``` --- #### 三、常见问题与解决方案 1. **配置文件加载失败** - **原因**:文件路径错误或资源未打包到JAR中。 - **解决**:使用类加载器读取资源: ```java InputStream input = getClass().getClassLoader().getResourceAsStream("app.properties"); ``` 2. **中文乱码** - **原因**:`.properties`文件默认使用ISO-8859-1编码。 - **解决**:改用`$new InputStreamReader(input, StandardCharsets.UTF_8)$`读取。 3. **时区与时间错误** - **现象**:Docker容器中Java程序日志时间不正确。 - **解决**:启动时设置系统属性`$-Duser.timezone=GMT+08$`: ```bash java -Duser.timezone=Asia/Shanghai -jar app.jar ``` 4. **敏感信息泄露** - **建议**:避免明文存储密码,使用加密工具(如Jasypt)处理。 --- #### 四、高级用法 1. **系统属性与环境变量** - 获取系统属性:`$System.getProperty("user.dir")$` - 环境变量:`$System.getenv("PATH")$` 2. **动态配置热更新** 结合Apache Commons Configuration或Spring Cloud Config实现。 --- §§ 1. 如何通过环境变量覆盖Java Properties文件中的配置? 2. Properties文件如何实现国际化多语言支持? 3. 在Spring Boot中如何优雅地管理Properties配置? 4. 如何加密Properties文件中的敏感数据? 5. Docker容器中Java应用时区不一致的根本原因是什么? : JavaBean属性遵循封装原则,通过getter/setter控制访问。 : Docker容器时区问题可通过设置`$-Duser.timezone$`解决。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值