java获取配置文件信息
package com.censoft.util; import java.util.Properties; import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; public class SafeProperties extends Properties {
private static final long serialVersionUID = 5011694856722313621L; private static final String keyValueSeparators = "=: \t\r\n\f"; private static final String strictKeyValueSeparators = "=:"; private static final String specialSaveChars = "=: \t\r\n\f#!"; private static final String whiteSpaceChars = " \t\r\n\f"; private PropertiesContext context = new PropertiesContext(); public PropertiesContext getContext() {
return context;
} public synchronized void load(InputStream inStream) throws IOException { BufferedReader in; in = new BufferedReader(new InputStreamReader(inStream, "8859_1"));
while (true) {
String line = in.readLine();
String intactLine = line;
if (line == null)
return; if (line.length() > 0) { int len = line.length();
int keyStart;
for (keyStart = 0; keyStart < len; keyStart++)
if (whiteSpaceChars.indexOf(line.charAt(keyStart)) == -1)
break; if (keyStart == len)
continue; char firstChar = line.charAt(keyStart); if ((firstChar != '#') && (firstChar != '!')) {
while (continueLine(line)) {
String nextLine = in.readLine();
intactLine = intactLine + "\n" + nextLine;
if (nextLine == null)
nextLine = "";
String loppedLine = line.substring(0, len - 1);
int startIndex;
for (startIndex = 0; startIndex < nextLine.length(); startIndex++)
if (whiteSpaceChars.indexOf(nextLine.charAt(startIndex)) == -1)
break;
nextLine = nextLine.substring(startIndex, nextLine.length());
line = new String(loppedLine + nextLine);
len = line.length();
} int separatorIndex;
for (separatorIndex = keyStart; separatorIndex < len; separatorIndex++) {
char currentChar = line.charAt(separatorIndex);
if (currentChar == '\\')
separatorIndex++;
else if (keyValueSeparators.indexOf(currentChar) != -1)
break;
} int valueIndex;
for (valueIndex = separatorIndex; valueIndex < len; valueIndex++)
if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1)
break; if (valueIndex < len)
if (strictKeyValueSeparators.indexOf(line.charAt(valueIndex)) != -1)
valueIndex++; while (valueIndex < len) {
if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1)
break;
valueIndex++;
}
String key = line.substring(keyStart, separatorIndex);
String value = (separatorIndex < len) ? line.substring(valueIndex, len) : ""; key = loadConvert(key);
value = loadConvert(value);
put(key, value, intactLine);
} else {
context.addCommentLine(intactLine);
}
} else {
context.addCommentLine(intactLine);
}
}
} private String loadConvert(String theString) {
char aChar;
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len); for (int x = 0; x < len;) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
// Read the xxxx
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException("Malformed \\uxxxx encoding.");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't')
outBuffer.append('\t'); /* ibm@7211 */ else if (aChar == 'r')
outBuffer.append('\r'); /* ibm@7211 */
else if (aChar == 'n') {
/*
* ibm@8897 do not convert a \n to a line.separator
* because on some platforms line.separator is a String
* of "\r\n". When a Properties class is saved as a file
* (store()) and then restored (load()) the restored
* input MUST be the same as the output (so that
* Properties.equals() works).
*
*/
outBuffer.append('\n'); /* ibm@8897 ibm@7211 */
} else if (aChar == 'f')
outBuffer.append('\f'); /* ibm@7211 */
else
/* ibm@7211 */
outBuffer.append(aChar); /* ibm@7211 */
}
} else
outBuffer.append(aChar);
}
return outBuffer.toString();
} public synchronized void store(OutputStream out, String header) throws IOException {
BufferedWriter awriter;
awriter = new BufferedWriter(new OutputStreamWriter(out, "8859_1"));
if (header != null)
writeln(awriter, "#" + header);
List<Object> entrys = context.getCommentOrEntrys();
for (Iterator<Object> iter = entrys.iterator();
iter.hasNext();) {
Object obj = iter.next();
if (obj.toString() != null) {
writeln(awriter, obj.toString());
}
}
awriter.flush();
} private static void writeln(BufferedWriter bw, String s) throws IOException {
bw.write(s);
bw.newLine();
} private boolean continueLine(String line) {
int slashCount = 0;
int index = line.length() - 1;
while ((index >= 0) && (line.charAt(index--) == '\\'))
slashCount++;
return (slashCount % 2 == 1);
} private String saveConvert(String theString, boolean escapeSpace) {
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len * 2); for (int x = 0; x < len; x++) {
char aChar = theString.charAt(x);
switch (aChar) {
case ' ':
if (x == 0 || escapeSpace)
outBuffer.append('\\'); outBuffer.append(' ');
break;
case '\\':
outBuffer.append('\\');
outBuffer.append('\\');
break;
case '\t':
outBuffer.append('\\');
outBuffer.append('t');
break;
case '\n':
outBuffer.append('\\');
outBuffer.append('n');
break;
case '\r':
outBuffer.append('\\');
outBuffer.append('r');
break;
case '\f':
outBuffer.append('\\');
outBuffer.append('f');
break;
default:
if ((aChar < 0x0020) || (aChar > 0x007e)) {
outBuffer.append('\\');
outBuffer.append('u');
outBuffer.append(toHex((aChar >> 12) & 0xF));
outBuffer.append(toHex((aChar >> 8) & 0xF));
outBuffer.append(toHex((aChar >> 4) & 0xF));
outBuffer.append(toHex(aChar & 0xF));
} else {
if (specialSaveChars.indexOf(aChar) != -1)
outBuffer.append('\\');
outBuffer.append(aChar);
}
}
}
return outBuffer.toString();
} /**
* Convert a nibble to a hex character
* @param nibble the nibble to convert.
*/
private static char toHex(int nibble) {
return hexDigit[(nibble & 0xF)];
} /** A table of hex digits */
private static final char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
'F' }; public synchronized Object put(Object key, Object value) {
context.putOrUpdate(key.toString(), value.toString());
return super.put(key, value);
} public synchronized Object put(Object key, Object value, String line) {
context.putOrUpdate(key.toString(), value.toString(), line);
return super.put(key, value);
} public synchronized Object remove(Object key) {
context.remove(key.toString());
return super.remove(key);
} class PropertiesContext {
private List<Object> commentOrEntrys = new ArrayList<Object>(); public List<Object> getCommentOrEntrys() {
return commentOrEntrys;
} public void addCommentLine(String line) {
commentOrEntrys.add(line);
} public void putOrUpdate(PropertyEntry pe) {
remove(pe.getKey());
commentOrEntrys.add(pe);
} public void putOrUpdate(String key, String value, String line) {
PropertyEntry pe = new PropertyEntry(key, value, line);
remove(key);
commentOrEntrys.add(pe);
} public void putOrUpdate(String key, String value) {
PropertyEntry pe = new PropertyEntry(key, value);
int index = remove(key);
commentOrEntrys.add(index,pe);
} public int remove(String key) {
for (int index = 0; index < commentOrEntrys.size(); index++) {
Object obj = commentOrEntrys.get(index);
if (obj instanceof PropertyEntry) {
if (obj != null) {
if (key.equals(((PropertyEntry) obj).getKey())) {
commentOrEntrys.remove(obj);
return index;
}
}
}
}
return commentOrEntrys.size();
} class PropertyEntry {
private String key; private String value; private String line; public String getLine() {
return line;
} public void setLine(String line) {
this.line = line;
} public PropertyEntry(String key, String value) {
this.key = key;
this.value = value;
} /**
* @param key
* @param value
* @param line
*/
public PropertyEntry(String key, String value, String line) {
this(key, value);
this.line = line;
} public String getKey() {
return key;
} public void setKey(String key) {
this.key = key;
} public String getValue() {
return value;
} public void setValue(String value) {
this.value = value;
} public String toString() {
if (line != null) {
return line;
}
if (key != null && value != null) {
String k = saveConvert(key, true);
String v = saveConvert(value, false);
return k + "=" + v;
}
return null;
}
}
} public void addComment(String comment) {
if (comment != null) {
context.addCommentLine("#" + comment);
}
} }
package com.censoft.util; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader; public class PropertyUtils { public static final String FILENAME ="solr.properties"; /**
* 根据KEY,读取文件对应的值 *
* filePath 文件路径,即文件所在包的路径,例如:java/util/config.properties *
*/
public static String getProp(String filename, String key) {
try {
SafeProperties safeProperty = new SafeProperties();
String filepath = PropertyUtils.class.getClassLoader().getResource("/").getPath() + filename; File file = new File(filepath);
InputStream in = new FileInputStream(file);
safeProperty.load(in);
in.close();
String value = safeProperty.getProperty(key);
return value;
} catch (Exception e){
e.printStackTrace();
return null;
}
} /**
* @param filename 文件名称
* @param key 键
* @param value 对应键需要修改的值
*/
public static void setProp(String filename, String key, String value) {
try {
SafeProperties safeProperty = new SafeProperties();
String filepath = PropertyUtils.class.getClassLoader().getResource("/").getPath() + filename;
File file = new File(filepath);
InputStream in = new FileInputStream(file);
safeProperty.load(in); // 一定要在修改值之前关闭fis
in.close();
OutputStream fos = new FileOutputStream(file);
safeProperty.setProperty(key, value); // 保存,并加入注释
safeProperty.store(fos, null);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 根据KEY,读取文件对应的值 *
* filePath 文件路径,即文件所在包的路径,例如:java/util/config.properties *
*/
public static String getProp(String key) {
try {
SafeProperties safeProperty = new SafeProperties();
String filepath = PropertyUtils.class.getClassLoader().getResource("/").getPath() + FILENAME; filepath = filepath.replace("classes/", "");
Reader inStream = new InputStreamReader(new FileInputStream(filepath), "UTF-8");
safeProperty.load(inStream); /* File file = new File(filepath);
InputStream in = new FileInputStream(file);
safeProperty.load(in);*/
inStream.close();
String value = safeProperty.getProperty(key);
return value;
} catch (Exception e){
e.printStackTrace();
return null;
}
} /**
* @param filename 文件名称
* @param key 键
* @param value 对应键需要修改的值
*/
public static void setProp( String key, String value) {
try {
SafeProperties safeProperty = new SafeProperties();
String filepath = PropertyUtils.class.getClassLoader().getResource("/").getPath() + FILENAME;
filepath = filepath.replace("classes/", "");
File file = new File(filepath);
InputStream in = new FileInputStream(file);
safeProperty.load(in); // 一定要在修改值之前关闭fis
in.close();
OutputStream fos = new FileOutputStream(file);
safeProperty.setProperty(key, value); // 保存,并加入注释
safeProperty.store(fos, null);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
java获取配置文件信息的更多相关文章
- Java 反射理解(三)-- Java获取方法信息
Java 反射理解(三)-- Java获取方法信息 基本的数据类型.void关键字,都存在类类型. 举例如下: public class ClassDemo2 { public static void ...
- SpringBoot项目中,获取配置文件信息
1.在配置文件中设置信息,格式如下 wechat: mpAppId: wxdf2b09f280e6e6e2 mpAppSecret: f924b2e9f140ac98f9cb5317a8951c71 ...
- SpringBoot配置分析、获取到SpringBoot配置文件信息以及几种获取配置文件信息的方式
Spring入门篇:https://www.cnblogs.com/biehongli/p/10170241.html SpringBoot的默认的配置文件application.properties ...
- 【java 获取数据库信息】获取MySQL或其他数据库的详细信息
1.首先是 通过数据库获取数据表的详细列信息 package com.sxd.mysqlInfo.test; import java.sql.Connection; import java.sql.D ...
- java获取天气信息
通过天气信息接口获取天气信息,首先要给项目导入程序所需要的包,具体需要如下几个包: json-lib-2.4.jar ezmorph-1.0.6.jar commons-beanutils-1.8.3 ...
- java获取泛型信息
总结一下java中获取与泛型相关的信息的知识,不如说是使用方法.网上也有很多类似的优秀文章,这里主要做一个知识的总结.通过反射获取泛型信息的常见例子: //bean package testProje ...
- 使用Spring注解获取配置文件信息
需要加载的配置文件内容(resource.properties): #FTP相关配置 #FTP的IP地址 FTP_ADDRESS=192.168.1.121 FTP_PORT=21 FTP_USERN ...
- 获取配置文件信息——configparser
配置文件host.int格式如下: [host]product=xxxxxxxxxxtest=xxxxxxxxxx python 3.x代码如下: import os,configparser def ...
- Java获取配置文件中的属性
获取配置文件的属性值 example 目标配置文件jdbc.properties,现想要在java类里面调用opcl的url jdbc.url=jdbc:mysql://localhost:3306/ ...
随机推荐
- CentOS LVM 卷在线扩容
场景: vmware 虚拟机,装了CentOS ,更改了虚拟机磁盘的大小:从200G,扩展到320G,可以参考本文写了步骤. 1. 在线扫描虚拟机SCSI新增的容量 # for i in `find ...
- Ado.NET SQLHelper(2)
测试发现前面发的那个功能太简单,不能调用getdate()等内部函数. 完善后重载了insert和update两个功能,将函数作为字符串传入SQL语句构造,需要的可以试用一下 using Sys ...
- 吴裕雄--天生自然java开发常用类库学习笔记:SortedSet接口
import java.util.SortedSet ; import java.util.TreeSet ; public class TreeSetDemo05{ public static vo ...
- IIC协议解析
(1)概述 I2C(Inter-Integrated Circuit BUS) 集成电路总线,该总线由NXP(原PHILIPS)公司设计,多用于主控制器和从器件间的主从通信,在小数据量场合使用,传输距 ...
- 我编写的EEPROM 上位机软件
进入模式: 上位机发送 消息 上位机EEPROM 按下进入模式 消息的ID号是:0x08111111 数据是: 00 01 ff 00 00 00 00 00 上位机显示 运行状态 :为进入模式 当我 ...
- 讨论(xia che ≖‿≖✧)magic number——1000000007
为什么要对1000000007取模(取余) 来看这篇博客的基本上都是和我一样脑子有坑的人,要么就是看了我某篇大数阶乘,大数的排列组合等类似博客被忽悠过来的.我刚刚说到那些类型的题目一般都要求将输出结果 ...
- C语言备忘录——取余与取模
前几天,一个小姐姐问我取余和取模有什么区别,我当时第一反应就是二者是一样的,但是小姐姐咬死说不一样.我去百度了一下还真的不一样.脑壳疼,我当初误导了多少人.所以为了帮助我记忆也为了帮助预防我误人子弟 ...
- windows 禁用中文输入法(转)
源博客地址:http://blog.csdn.net/xie1xiao1jun/article/details/17913967 windows 程序禁用中文输入法方法:1.添加windows头文件及 ...
- 存储器HK1225-7EQ 使用说明书资料
一. 引脚排列 二. 读取模式 HK1225在WE(写使能)被禁止(high)且CE(片选)被选中(Low)且CE2(片选2)被选中(High)并且OE(读信号)被使能(Low)执行一次读循环.13个 ...
- Spring Boot2(005):关于代码结构
spring boot 对于工程代码结构并没有特殊得要求,但以下几个有用的最佳实践建议参考参考: 1.不鼓励而且应该避免使用 default 包 没有 package 声明的类被认为是在 defaul ...