实例截图:

java 操作Properties文件查询与添加修改 io 读写_json

java 操作Properties文件查询与添加修改 io 读写_java_02

实例代码

package com.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
* 操作Properties文件 io读写
* @author yushen
*
*/
public class TestProperties {

/**
* 测试Properties
* @param args
*/
public static void main(String[] args) {
//获取系统路径
String FileUrl = System.getProperty("user.dir")+"/src/config/csd.properties";

//如果已经有了key 会替换之前的key value
String key = "jdbc";
String value = "oracle:1521";
String notes = "00几数据库配置文件!";
int cbo = putPropertiesKeyValue(FileUrl, key, value, notes);
System.out.println("数据添加"+(cbo == 0 ? "成功!" : "失败!"));

String QueryValue = getPropertiesValueID(FileUrl,key);
System.out.println("返回的"+key+"字段查询数据为:"+QueryValue);

JSONObject jo = getPropertiesValueAll(FileUrl);
System.out.println("返回的全部数据是:"+jo);

}

/**
* 给Properties文件添加数据
* @param Url 文件路径
* @param key 添加字段key
* @param value 添加字段value
* @param Notes 添加字段注释
* @return 返回0成功,返回1失败
*/
public static int putPropertiesKeyValue(String Url,String key,String value,String Notes){
int retBoo = 0;
Properties prop = new Properties();
try {
FileOutputStream oFile = new FileOutputStream(Url, true);
prop.setProperty(key, value);
prop.store(oFile, Notes);
oFile.close();
retBoo = 0;
} catch (Exception e) {
System.out.println(e);
retBoo = 1;
}
return retBoo;
}

/**
* 单独查询Properties文件的某个key 返回String
* @param Url
* @param key
* @return String
*/
public static String getPropertiesValueID(String Url,String key){
String restValue = "";
Properties prop = new Properties();
try {
InputStream in = new BufferedInputStream(new FileInputStream(Url));
prop.load(in);
restValue = prop.getProperty(key);
}catch (Exception e) {
System.out.println(e);
}
return restValue;
}

/**
* 查询Properties文件所有内容
* @param Url
* @return JSONObject
*/
public static JSONObject getPropertiesValueAll(String Url){
JSONObject jo = new JSONObject();
Properties prop = new Properties();
try {
InputStream in = new BufferedInputStream(new FileInputStream(Url));
prop.load(in);
Iterator<String> it = prop.stringPropertyNames().iterator();
while (it.hasNext()) {
String key = it.next();
jo.put(key, prop.getProperty(key));
}
in.close();
}catch (Exception e) {
System.out.println(e);
}
return jo;
}
}