1.读取properties:
代码:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
public class PropertiesUtil {
/**
* 获取指定路径下对应properties文件中的值
* @param propertiesPath
* @param key
* @return
*/
public static String readProperties(String propertiesPath,String key){
String re=null;
Properties prop = new Properties(); //创建Properties对象
InputStream in = null;
try {
in = new FileInputStream(propertiesPath); //创建输入流文件对象
prop.load(in);
re=prop.getProperty(key);//加载输入流
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
in.close(); //关闭输入流
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
return re;
}
/**
* 通过文件名获取构建路径下对应的properties文件中的值
* @param propertiesName
* @param key
* @return
*/
public static String readPropertiesByConfigName(String propertiesName,String key){
String re=null;
Properties prop = new Properties();
try {
InputStream input = PropertiesUtil.class.getClassLoader().getResourceAsStream(propertiesName);
prop.load(input);
String data = prop.getProperty(key);
return data;
}catch (Exception e){
e.printStackTrace();
}
return re;
}
public static void main(String[] args) {
String re=readPropertiesByConfigName("pathConfig.properties","file.uploadDownLoad.path");
System.out.println(re);
}
}
实例:
private static final String userConfigProperties_Path="E:\\JAVA_Space\\dubbo\\src\\main\\resources\\userConfig.properties";
public static void main(String[] args) {
String re=PropertiesUtil.readProperties(userConfigProperties_Path,"a1");
System.out.println(re);
}
测试结果:
2.写入properties文件
代码:
/**
* 写入properties
* @param propertiesPath
* @param key
* @param value
*/
public static void writeProperties(String propertiesPath,String key,String value) {
Properties prop = new Properties(); //创建Properties对象
InputStream in = null;
FileOutputStream oFile = null;
try {
in = new FileInputStream(propertiesPath); //创建输入流文件对象
prop.load(in); //加载输入流
prop.setProperty(key, value); //修改值
oFile = new FileOutputStream(propertiesPath); //创建输出流文件对象
prop.store(oFile, ""); //将Properties对象的属性保存到输出流指定文件
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
oFile.close(); //关闭输出流
} catch (Exception e) {
System.out.println(e.getMessage());
}
try {
in.close(); //关闭输入流
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
实例:
private static final String userConfigProperties_Path="E:\\JAVA_Space\\dubbo\\src\\main\\resources\\userConfig.properties";
public static void main(String[] args) {
PropertiesUtil.writeProperties(userConfigProperties_Path,"a1","qwertyuiop");
}
测试结果: