上代码:
import java.io.*;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class XMLUtil {
//写入xml文件
public static void storeTOXML(Properties properties,OutputStream outputStream,String comment) throws IOException {
storeTOXML(properties,outputStream,comment,"UTF-8");
}
public static void storeTOXML(Properties properties,OutputStream outputStream,String comment,String encoding) throws IOException {
properties.storeToXML(outputStream,comment,encoding);
}
public static void storeTOXML(Properties properties, File file, String comment) throws IOException {
storeTOXML(properties,file,comment,"UTF-8");
}
public static void storeTOXML(Properties properties,File file,String comment,String encoding) throws IOException {
properties.storeToXML(new FileOutputStream(file),comment,encoding);
}
//读取xml文件
public static void loadFromXML(Properties properties,File file) throws IOException {
loadFromXML(properties,new FileInputStream(file));
}
public static void loadFromXML(Properties properties,InputStream inputStream) throws IOException {
properties.loadFromXML(inputStream);
}
//写入文件
// public static void main(String[] args) {
// File file = Paths.get("aa","bb.xml").toFile();
// if (!file.getParentFile().exists())
// file.getParentFile().mkdirs();
// Properties properties = new Properties();
// properties.setProperty("nn","南宁");
// properties.setProperty("bh","北海");
//
// try {
// storeTOXML(properties,file,"我是注释");
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//读取文件
public static void main(String[] args) {
File file = Paths.get("aa","bb.xml").toFile();
Properties properties = new Properties();
try {
loadFromXML(properties,file);
properties.list(System.out);//控制台打印所以属性
//根据key获取属性
System.out.println("-- 根据key获取属性 --");
System.out.println(properties.getProperty("nn"));
System.out.println(properties.getProperty("bh"));
//获取所有键值
System.out.println("-- 获取所有键值(推荐使用Iterator方式读取集合) --");
Set<Map.Entry<Object, Object>> set = properties.entrySet();
Iterator<Map.Entry<Object, Object>> iterator = set.iterator();
while (iterator.hasNext()){
Map.Entry<Object,Object> me = iterator.next();
System.out.println(me.getKey()+"-->"+me.getValue());
}
System.out.println("-- 获取所有键值2(foreach方式读取) --");
Set<Map.Entry<Object, Object>> set2 = properties.entrySet();
for (Map.Entry<Object,Object> me:set2) {
System.out.println(me.getKey()+"-->"+me.getValue());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
文件内容: