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();
}
}
}
<?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();
}
}
}
- 源码.rar (4.9 KB)
- 下载次数: 1
相关推荐
在Java编程中,读取配置文件是常见的任务,特别是在开发需要灵活配置的系统时。配置文件通常用于存储应用程序的设置,如数据库连接信息、服务器端口、第三方服务的API密钥等,这些信息可能需要根据不同的环境或需求...
JAVA 高手解析 XML 配置文件的读取操作 本文主要讲解了 Java 中如何读取 XML 配置文件,并对 XML 解析器进行了分类,分别介绍了 DOM 和 SAX 两种解析方式的特点和使用场景,并提供了一个使用 SAX 解析器读取 XML ...
使用 Java 读取 XML 配置文件 Java 语言和 XML 技术可以说是黄金组合,网上已经有很多文章介绍 XML 在电子商务中的数据交换的作用。但是在平时系统开发中,我们不一定都用到数据交换,是否无法使用 XML?当然不是...
在Java编程中,读取配置文件是常见的任务,特别是在构建可扩展和可维护的应用程序时。配置文件通常用于存储应用程序的设置、连接信息或其他敏感数据,这样可以将这些信息与核心代码分离,便于管理和更新。本篇文章将...
在Java编程中,读取配置...总结来说,Java中读取配置文件的关键在于使用合适的工具或类(如`Properties`)来解析文件,并确保正确处理异常情况。在实际项目中,考虑将配置管理抽象化,以提高代码的可维护性和灵活性。
Java中XML配置文件的读取(SAX) XML配置文件是Java开发中常用的配置文件格式,特别是在J2EE项目中。XML文件可以存储配置信息,并且易于维护和修改。然而,在Java中读取XML配置文件成了一个需要解决的问题。本文将...
这是一个简单实现读取properties、xml格式的配置文件的小案例。虽然实际项目中可能不是这样实现的。作为了解也是不错的。 一、读取properties类型文件 方法一:java.util.ResourceBundle读取properties类型文件; ...
本压缩包包含两个工具类,分别用于读取`.yml`和`.properties`格式的配置文件,这两种格式都是Java开发中常见的配置文件类型。 首先,我们来看`.properties`配置文件。这种格式的文件历史较为悠久,它的语法简单,每...
在Java编程中,读取配置文件是常见的任务,它允许我们分离程序的配置信息,使得配置可以独立于代码进行修改,提高程序的可维护性和灵活性。这篇内容将深入讲解Java如何读取XML、INI等不同类型的配置文件。 一、XML...
### JAVA读取数据库的XML配置文件 #### 前言 在软件开发中,数据库配置信息的管理至关重要。随着技术的发展,出现了许多优秀的框架来帮助开发者处理这些任务,例如Hibernate等ORM(对象关系映射)工具,它们简化了...
总结起来,Java提供了多种方式来读取配置文件,包括使用`Properties`类处理.properties文件以及DOM、SAX或JAXB解析器处理.xml文件。了解这些方法可以帮助开发者更好地管理应用程序的配置信息,提高代码的可维护性和...
本文将深入探讨如何使用Java读取资源文件,特别是properties类型的文件。 资源文件通常存储在项目的类路径(classpath)下,可以是.properties、.txt、.xml等形式,它们提供了与代码分离的配置选项。对于....
在Java开发中,XML和properties配置文件是常见的数据存储和管理格式,用于存储应用程序的配置信息、数据库连接参数等。理解如何读取这两种类型的配置文件对于Java开发者来说至关重要。 1. **XML文件**: - **定义*...
当我们的应用程序被打包成JAR文件后,有时我们需要从JAR内部读取配置文件,例如application.properties或application.yml。本文将深入探讨如何在Spring框架中实现这一功能。 首先,理解Spring的资源配置。Spring...
Apache Commons Configuration库提供了一个强大的工具集,用于处理各种类型的配置文件,包括properties和XML格式。这个库使得在运行时对配置进行【增删改查】操作变得简单,同时支持动态加载,从而实现配置的实时...
这篇博客“spring mvc 读取配置文件”将深入探讨如何在Spring MVC中读取和使用配置文件,以及相关工具的应用。 首先,Spring MVC中的配置文件通常是指XML配置文件,如`applicationContext.xml`或`servlet-context....
2. 使用Properties类读取配置文件 Java提供了`java.util.Properties`类来处理.properties文件。首先,我们需要加载配置文件,然后获取其中的属性: ```java import java.io.FileInputStream; import java.io....