`
z_gxjs
  • 浏览: 7205 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

阅读更多
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();
}
}

}




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());
}
}
}




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();
}
}

}
分享到:
评论

相关推荐

    读取properties、xml格式的配置文件的实例

    这是一个简单实现读取properties、xml格式的配置文件的小案例。虽然实际项目中可能不是这样实现的。作为了解也是不错的。 一、读取properties类型文件 方法一:java.util.ResourceBundle读取properties类型文件; ...

    读取配置文件工具类.rar

    工具类里分读取.yml工具类和.properties工具类,结合博客描述使用,用不到的方法可根据个人情况删除,

    Java开发中读取XML与properties配置文件的方法

    主要介绍了Java开发中读取XML与properties配置文件的方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下

    conf:使用Java读取各种配置文件的类库

    这是一个解决Java开发中读取配置文件每次都要重写的困惑。 特性 开箱即用,简单方便 支持JDK1.6+ 无需过多依赖,按需添加 状态 [已完成] 解析Properties配置文件 [待完成] 解析Xml配置文件 [待完成] 解析Ini配置...

    Java Application下读取properties配置文件

    在java应用程序开发中,经常需要读取配置文件来获取系统参数或配置信息。配置文件可以使用xml格式文件,在java中存在.properties文件专门用作配置文件使用。在java中,类Properties用于处理配置文件相关的读取。下面...

    读Properties配置文件

    写好的读取properties配置文件的PropertiesConfig.java类,只需new个对象,PropertiesConfig config = new PropertiesConfig(); config.setPropertiesDataSource("/jdbc.properties"); config.getString(...

    tool-link-properties:读取项目配置文件

    将配置文件log4j2.xml和spring-logging.xml从项目目录转移至tool-logging的包目录。 更改“自定义变量”使用“远程配置读取”方式的规则,["dev","test","real"]远程读取,其他则配置文件读取。 更改“全局变量”jsp...

    Java加载资源文件的两种方法

     当我们自己的程序需要处理配置文件时(比如xml文件或properties文件),通常会遇到两个问题:  (1)我的配置文件应该放在哪里?  (2)怎么我的配置文件找不到了?  在了解了Java加载资源文件的机制后...

    jdbc.properties

    当配置文件用,在里面读取一些关于路径方面的设置(如ant中的build.properties) 存放一组配置.(类似win下ini, 还要简单些, 因为没有section) 由于难以表达层次, 复杂点可以用xml做配置. 通俗点讲就相当于定义一个...

    整合activiti.cfg.xml文件到资源文件

    activiti.cfg.xml和application.properties文件的整合配置,不能两个都存在,方便,适应

    一个Java配置文件加密解密工具类分享

    在 JavaEE 配置文件中,例如 XML 或者 properties 文件,由于某些敏感信息不希望普通人员看见,则可以采用加密的方式存储,程序读取后进行解密

    commons-configuration代码实例

    commons configuration读取配置文件的例子,包括properties文件,ini文件和xml文件

    Java高级程序设计实战教程第三章-Java反射机制.pptx

    应用程序通过读取配置文件来获取到指定名称的类的字节码文件并加载其中的内容进行调用,对一个类文件进行解剖,就可以取得任意一个已知名称的class的内部信息,包括其modifiers(诸如public,static等等)、...

    研磨设计模式之单例模式

     单例模式(Singleton)1 场景问题1.1 读取配置文件的内容考虑这样一个应用,读取配置文件的内容。很多应用项目,都有与应用相关的配置文件,这些配置文件多是由项目开发人员自定义的,在里面定义一些应用需要的...

    数据库连接池druid,c3p0,jdbctemplate,jar包.rar

    数据库连接池jar包,包含c3p0、druidjar包和依赖jar包,c3p0通过配置文件xml或者properties读取连接对象 druid通过properties读取连接,使用springJDBC JdbcTempalte简化sql操作

    JAVA 范例大全 光盘 资源

    常见问题 读取Properties文件出现中文乱码 182 第9章 Java异常处理与反射机制 183 实例73 运用throws、throw、try与catch 183 实例74 throws声明异常的实例 185 实例75 自定义异常类 187 实例76 使用finally...

    将 Flex 集成到 Java EE 应用程序的最佳实践(完整源代码)

    BlazeDS 将读取 services-config.xml 配置文件,该配置文件又引用了 remoting-config.xml、proxy-config.xml 和 messaging-config.xml 这 3 个配置文件,所以,一共需要 4 个配置文件。 由于 BlazeDS 需要将 Java ...

    +Flex+集成到+Java+EE+应用程序的最佳实践(完整源代码)

    BlazeDS 将读取 services-config.xml 配置文件,该配置文件又引用了 remoting-config.xml、proxy-config.xml 和 messaging-config.xml 这 3 个配置文件,所以,一共需要 4 个配置文件。 由于 BlazeDS 需要将 Java ...

Global site tag (gtag.js) - Google Analytics