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"));
}
}
分享到:
相关推荐
java 读取properties文件代码
java读写properties文件,解决系统找不到指定路径,解决写入后读取正常,但文件数据未更新问题
Java读取Properties文件的六种方法
JAVA读取properties的值,JAVA读取properties文件,JAVA读取properties的内容
java读写properties配置文件
java读取properties文件的工具类,传入配置文件名字和其中的key就可以读取
java读取properties文件,没有用到了第三方jar包,方便实用
java读写properties文件,解决系统找不到指定路径,解决写入后读取正常,但文件数据未更新问题
NULL 博文链接:https://xieke90.iteye.com/blog/2233046
java实现properties文件读取
java如何读取properties配置文件
主要介绍了java读取properties文件的方法,实例分析了java操作properties配置文件的相关技巧,需要的朋友可以参考下
java对properties配置文件的读和写
利用Java的Properties 类读取配置文件信息! 读取Properties文件的例子
主要介绍了java读取properties文件的方法,实例分析了java读取在项目中与不在项目中properties文件的相关技巧,需要的朋友可以参考下
解决JAVA读取properties中文乱码问题
NULL 博文链接:https://duanfei.iteye.com/blog/565672