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");
}
測試結果: