java读取配置文件xml ,properties,txt

1 篇文章 0 订阅
1 篇文章 0 订阅
[color=green]1、读取.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="B01">
<name>哈里波特</name>
<price>10</price>
<memo>这是一本很好看的书。</memo>
</book>
<book id="B02">
<name>三国演义</name>
<price>10</price>
<memo>四大名著之一。</memo>
</book>
<book id="B03">
<name>水浒</name>
<price>6</price>
<memo>四大名著之一。</memo>
</book>
<book id="B04">
<name>红楼</name>
<price>5</price>
<memo>四大名著之一。</memo>
</book>

</books>

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.*;
import javax.xml.xpath.*;

public class ExecuteXmlUtil {

private ExecuteXmlUtil() {
}

private static String filePath = "WebRoot/WEB-INF/classes/socket.xml";
private static Element theChild = null, theElem = null, root = null;

public static void main(String[] args) {
delete();
}

public static void add(){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = factory.newDocumentBuilder();
Document xmldoc = db.parse(new File(filePath));
root = xmldoc.getDocumentElement();

theChild = xmldoc.createElement("book");
theElem = xmldoc.createElement("name");
theElem.setTextContent("新书");
theChild.appendChild(theElem);

theElem = xmldoc.createElement("price");
theElem.setTextContent("20");
theChild.appendChild(theElem);
theElem = xmldoc.createElement("memo");
theElem.setTextContent("新书的更好看。");
theChild.appendChild(theElem);
root.appendChild(theChild);
saveXml(filePath, xmldoc);

output(xmldoc);
} catch (DOMException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void update(){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = factory.newDocumentBuilder();
Document xmldoc = db.parse(new File(filePath));
root = xmldoc.getDocumentElement();
theChild = (Element) selectSingleNode("/books/book[name='哈里波特']",root);
theChild.getElementsByTagName("price").item(0).setTextContent("100");

saveXml(filePath, xmldoc);

output(xmldoc);
} catch (DOMException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void delete(){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = factory.newDocumentBuilder();
Document xmldoc = db.parse(new File(filePath));
root = xmldoc.getDocumentElement();
theChild = (Element) selectSingleNode("/books/book[@id='B01']", root);
theChild.getParentNode().removeChild(theChild);

NodeList someBooks = selectNodes("/books/book[price<10]", root);
for (int i = 0; i < someBooks.getLength(); i++) {
someBooks.item(i).getParentNode().removeChild(someBooks.item(i));
}

saveXml(filePath, xmldoc);

output(xmldoc);
} catch (DOMException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 将node的XML字符串输出到控制台
* @param node
*/
public static void output(Node node) {
TransformerFactory transFactory = TransformerFactory.newInstance();
try {
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty("encoding", "UTF-8");
transformer.setOutputProperty("indent", "yes");
DOMSource source = new DOMSource();
source.setNode(node);
StreamResult result = new StreamResult();
result.setOutputStream(System.out);

transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}

/**
* 查找节点,并返回第一个符合条件节点
* @param express
* @param source
* @return
*/
public static Node selectSingleNode(String express, Object source) {
Node result = null;
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
try {
result = (Node) xpath
.evaluate(express, source, XPathConstants.NODE);
} catch (XPathExpressionException e) {
e.printStackTrace();
}

return result;
}

/**
* 查找节点,返回符合条件的节点集
* @param express
* @param source
* @return
*/
public static NodeList selectNodes(String express, Object source) {
NodeList result = null;
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
try {
result = (NodeList) xpath.evaluate(express, source,
XPathConstants.NODESET);
} catch (XPathExpressionException e) {
e.printStackTrace();
}

return result;
}

/**
* 将Document输出到文件
* @param fileName
* @param doc
*/
public static void saveXml(String fileName, Document doc) {
TransformerFactory transFactory = TransformerFactory.newInstance();
try {
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty("encoding", "UTF-8");
transformer.setOutputProperty("indent", "yes");
DOMSource source = new DOMSource();
source.setNode(doc);
StreamResult result = new StreamResult();
result.setOutputStream(new FileOutputStream(fileName));

transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

}[/color]


[color=red]
2、读取.properties文件
socket_dm=false

train_ip=192.168.0.240
train_port=28850

tree_ip=192.168.0.240
tree_port=28850

ftree_ip=192.168.0.240
ftree_port=28850

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;

public class ExecutePropertiesUtil {

private static String filePath="WebRoot/WEB-INF/classes/socket.properties";

private ExecutePropertiesUtil() {
}

/**
* @explain 测试类
*/
public static void main(String[] args) {
// 如果 在前台页面请调用此方法 webFilePath();
readValue("train_ip");
writeProperties("train_ip", "127.0.0.1");
readProperties();
}

/**
* @explain 获取配置文件路径 程序发布filePath应该是执行此方法然后才能得到的路径
*/
public static String webFilePath(){
try {
filePath = new File("").getCanonicalPath();
if ("bin".equals(filePath.substring(filePath.length()-3,filePath.length()))) {
filePath = filePath.substring(0,filePath.length()-3);
filePath+="/webapps/zhangycUtil/WEB-INF/classes/socket.properties";
}else{
filePath+="/webapps/zhangycUtil/WEB-INF/classes/socket.properties";
}
System.out.println("加载配置文件路径:"+filePath);
} catch (IOException e) {
System.out.println("加载配置文件路径异常:"+e.getMessage());
}
return filePath;
}

// 根据key读取value
public static String readValue(String key) {
Properties props = new Properties();
String value = "";
try {
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
props.load(in);
value = props.getProperty(key);
System.out.println("根据key读取value:key:["+key+"] \t value:" + value);
return value;
} catch (Exception e) {
System.out.println("根据key读取value异常:key:"+key+",value:" + value+",异常信息"+e.getMessage());
return null;
}

}

// 读取properties的全部信息
@SuppressWarnings("unchecked")
public static void readProperties() {
Properties props = new Properties();
try {
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
props.load(in);
Enumeration en = props.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String Property = props.getProperty(key);
System.out.println("读取配置文件:key:"+key+",value:" + Property);
}
} catch (Exception e) {
System.out.println("读取配置文件异常" + e.getMessage());
}
}

// 写入properties信息
public static void writeProperties(String parameterName,String parameterValue) {
Properties prop = new Properties();
try {
InputStream fis = new FileInputStream(filePath);
// 从输入流中读取属性列表(键和元素对)
prop.load(fis);
// 调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。
// 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
OutputStream fos = new FileOutputStream(filePath);
prop.setProperty(parameterName, parameterValue);
// 以适合使用 load 方法加载到 Properties 表中的格式,
// 将此 Properties 表中的属性列表(键和元素对)写入输出流
prop.store(fos, "Update '" + parameterName + "' value");
System.out.println("修改配置文件:key:"+parameterName+",value:" + parameterValue);
} catch (IOException e) {
System.out.println("修改配置文件异常:key:"+parameterName+",value:" + parameterValue+ " value error"+e.getMessage());
}
}
}[/color]


[color=blue]3、读取.txt文件
socket_dm=false

train_ip=192.168.0.240
train_port=28850

tree_ip=192.168.0.240
tree_port=28850

ftree_ip=192.168.0.240
ftree_port=28850

package org.zyc.common.util;

import java.io.*;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

/**
* @功能描述:创建TXT文件并进行读、写、修改操作
*/
public class ExecuteTxtUtil {

private ExecuteTxtUtil() {
}

// 指定文件路径和名称
private static String filePath = "WebRoot/WEB-INF/classes/socket.txt";

// 测试
public static void main(String[] args) throws IOException {
delTxtByStr("ap_ip=127.168.0.1");
writeTxtFile("ap_ip=192.168.0.1");
replaceTxtByStr("192","127");
writeTxtFile("ap_ip=192.168.0.2");
readTxtFile();
}

/**
* 读取文件
*/
public static String readTxtFile() {
String readStr = "";
String read = new String();
try {
FileReader fileread = new FileReader(new File(filePath));
BufferedReader bufread = new BufferedReader(fileread);
try {
while ((read = bufread.readLine()) != null) {
readStr = readStr + read + "\r\n";
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("读取到的内容是:"+readStr);
return readStr;
}

/**
* 添加 添加到文本的最后一行
* @param newStr 要添加的内容
*/
public static void writeTxtFile(String str) throws IOException {
delSpace ();
String oldStr = new String();
String newStr = new String();
try {
File file = new File(filePath);
if (!file.exists()) {
file.createNewFile();
System.err.println(file + "已创建!");
}
BufferedReader input = new BufferedReader(new FileReader(file));
while ((oldStr = input.readLine()) != null) {
newStr += oldStr + "\n";
}
input.close();
newStr += "\n" + str;
BufferedWriter output = new BufferedWriter(new FileWriter(file));
output.write(newStr);
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 修改文件内容 查找替换
* @param oldStr 查找内容
* @param replaceStr 替换内容
*/
public static void replaceTxtByStr (String oldStr,String replaceStr){
delSpace ();
String temp="";
try {
FileInputStream fis = new FileInputStream(filePath);
byte[] b = new byte[2000];
while (true) {
int i = fis.read(b);
if (i == -1){
break;
}
temp = temp + new String(b, 0, i);
}
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
temp = temp.replaceAll(oldStr, replaceStr);
try {
// true原有续写,false是追加。如果源文件不存在就新建了
FileOutputStream fos = new FileOutputStream(filePath, false);
fos.write(temp.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 删除文件内容
* @param oldStr 查找内容
* @throws Exception
*/
public static void delTxtByStr (String oldStr) {
delSpace ();
String readStr = "";
String read = new String();
try {
FileReader fileread = new FileReader(new File(filePath));
BufferedReader bufread = new BufferedReader(fileread);
try {
while ((read = bufread.readLine()) != null) {
if(!oldStr.equals(read)){
readStr = readStr + read + "\r\n";
}
}
BufferedWriter output = new BufferedWriter(new FileWriter(new File(filePath)));
output.write(readStr);
output.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

/**
* 去除空格和重复数据
*/
@SuppressWarnings("unchecked")
public static void delSpace (){
Set values = new LinkedHashSet();
String newStr = new String();
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
String value = "";
while ((value = bf.readLine()) != null) {
if (!value.equals("")) {
values.add(value);
}
}
Iterator it = values.iterator();
while (it.hasNext()) {
newStr += "\r\n" + it.next();
}
BufferedWriter output = new BufferedWriter(new FileWriter(new File(filePath)));
output.write(newStr);
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}[/color]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值