import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Properties;
public class Test {
//path需要文件的绝对路径
public static String readProperties(String fileName, String parameterName) {
String filePath=Test.class.getResource("/")+"";
//替换所获得路径的/bin为/src
//conf/表示配置文件所在的包名,根据不同的包进行修改
String fPath=filePath.replaceAll("/bin","/src")+"conf/"+fileName;
//去掉path前面的file:/
String path = fPath.replaceAll("file:/","");
System.out.println(path);
File file = new File(path);
String value = "";
Properties prop = new Properties();
try {
InputStream fis = new FileInputStream(file);
prop.load(fis);
value = prop.getProperty(parameterName);
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
public static Properties readProperties2(String fileName, String parameterName) {
String filePath=Test.class.getResource("/")+"";
String fPath=filePath.replaceAll("/bin","/src")+"conf/"+fileName;
String path = fPath.replaceAll("file:/","");
System.out.println(path);
File file = new File(path);
Properties prop = new Properties();
try {
InputStream fis = new FileInputStream(file);
prop.load(fis);
// value = prop.getProperty(parameterName);
} catch (Exception e) {
e.printStackTrace();
}
return prop;
}
public static void writeProperties(Properties prop,String fileName){
String filePath=Test.class.getResource("/")+"";
String fPath=filePath.replaceAll("/bin","/src")+"conf/"+fileName;
String path = fPath.replaceAll("file:/","");
System.out.println(path);
File file = new File(path);
try {
OutputStream fos = new FileOutputStream(file);
// 调用 Hashtable 的方法 put。
prop.setProperty("jdbc.url", "新的字符串");
// 以适合使用 load 方法加载到 Properties 表中的格式,
// 将此 Properties 表中的属性列表(键和元素对)写入输出流
prop.store(fos, "Update '" + "x" + "' value");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]){
String fileName="1.properties";
Properties properties = readProperties2(fileName,"jdbc.url");
writeProperties(properties,fileName);
System.out.println(readProperties(fileName,"jdbc.url"));
}
}