一、编写
通过Java基础的学习,我们了解了Properties这种文本格式,Java程序通过专门的API可以很方便的与之进行交互。但是我们每次对Properties进行写入或读取时都要创建I/O流来操作,有一些重复繁琐的地方,故我们可以创建Properties工具类来帮我们进一步简化操作。
如下:
import java.io.*;
import java.util.Properties;
public class PropertiesUtil {
// 创建默认的properties文件路径
public static final String PATH = "";
// 通过默认文件路径读取数据
public static String readProerties(String key) {
return readProerties(PATH, key);
}
// 通过默认文件路径写入数据
public static boolean storeProperties(String key, String value) {
return storeProperties(PATH, key, value);
}
// 通过 指定文件路径 和 key 读取对应的 value 值
public static String readProerties(String filePath, String key) {
Properties properties = readAllProperties(filePath);
return properties.getProperty(key);
}
// 通过 指定文件路径 和 key与value 存入数据
public static boolean storeProperties(String filePath, String key, String value) {
File file = new File(filePath);// 创建文件对象
FileOutputStream fos = null;
OutputStreamWriter os = null;
try {
if (!file.exists()) {// 如果文件不存在 则创建文件
file.createNewFile();
}
Properties allProperties = readAllProperties(filePath);// 通过文件路径,获得对应的properties 对象
allProperties.setProperty(key, value);// 将数据 写入 properties 对象
fos = new FileOutputStream(filePath);
os = new OutputStreamWriter(fos, "utf-8");
allProperties.store(os, "");// 将 properties 对象 中的数据存储到 properties文件中
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
// 此方法可通过文件路径,获得对应的properties 对象
public static Properties readAllProperties(String filePath) {
FileInputStream fis = null;
InputStreamReader is = null;
try {
fis = new FileInputStream(filePath);// 由文件路径创建 字节输入流
is = new InputStreamReader(fis, "utf-8");
Properties p = new Properties();// 创建 properties 对象
p.load(is);// 将字节输入流的数据载入 properties 对象
return p;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
二、使用
读取
// 通过指定properties文件路径和key值 获取对应的 value值
String DRIVER = PropertiesUtil.readProerties("src/homework/task1.properties", "DRIVER");
写入
// 通过指定properties文件路径和key-value值,进行一条键值对数据的写入
PropertiesUtil.storeProperties("src/homework/task1.properties","DRIVER","com.mysql.jdbc.Driver");