package com.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
* XML操作帮助类 文件操作帮助类
* @author xinjiatao
*
*/
public class XmlUtil {
/**
* 将Dom 读到另一个文件
*
* @param dom
* @param ifile
* @return
*/
public static int writeXMLPretty(Document dom, String ifile) {
int retVar = 1;
try {
OutputStream out;
File file = new File(ifile);
if (!file.exists()) {
if (!(file.getParentFile().exists())
&& !(file.getParentFile().mkdirs())) {
return 1;
}
}
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
out = new FileOutputStream(file);
XMLWriter wr = new XMLWriter(out, format);
wr.write(dom);
wr.close();
retVar = 0;
} catch (FileNotFoundException fe) {
fe.printStackTrace();
} catch (UnsupportedEncodingException ue) {
ue.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return retVar;
}
/**
* 在一个XML中, 删除指定的节点
*
* @param elmDevice
* 一个xml节点
* @param elmDel
* 要删除的一个节点
*/
public static void selectDelXmlNode(Element elmDevice, Element elmDel) {
for (Iterator it = elmDevice.elementIterator(); it.hasNext();) {
Element element = (Element) it.next();
int attCount = element.attributeCount();
int passCount = elmDel.attributeCount();
if (attCount == passCount) {
int count = 0;
for (int k = 0; k < attCount; k++) {
String devName = element.attribute(k).getName();
String devVal = element.attribute(k).getValue();
// 要删除的节点
String passName = element.attribute(k).getName();
String passVal = element.attribute(k).getValue();
if (devName.equals(passName) && devVal.equals(passVal)
&& attCount == passCount) {
count++;
}
}
if (count == passCount) {
Element e = element.getParent();
e.remove(element);
}
}
selectDelXmlNode(element, elmDel);
}
}
/**
* 读取XML返回Dom
*
* @param reader
* @return
*/
public static Document readXml(Reader reader) {
SAXReader sreader = new SAXReader();
try {
return sreader.read(reader);
} catch (DocumentException de) {
de.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
reader.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
/**
* 修改XML节点
*
* @param elmDevice
* 要修改的XML
* @param elmOld
* 之前的XML 节点
* @param newElm
* 修改后的XML节点
*/
public static void selectModifyXmlNode(Element elmDevice, Element elmOld,
Element newElm) {
for (Iterator it = elmDevice.elementIterator(); it.hasNext();) {
Element element = (Element) it.next();
int attCount = element.attributeCount();
int passCount = elmOld.attributeCount();
int newCount = newElm.attributeCount();
if (attCount == passCount && passCount == newCount) {
int count = 0;
for (int k = 0; k < attCount; k++) {
String devName = element.attribute(k).getName();
String devVal = element.attribute(k).getValue();
String passName = elmOld.attribute(k).getName();
String passVal = elmOld.attribute(k).getValue();
if (devName.equals(passName) && devVal.equals(passVal)
&& attCount == passCount) {
count++;
}
}
if (count == passCount) {
for (int i = 0; i < element.attributeCount(); i++) {
for (int j = 0; j < newElm.attributeCount(); j++) {
if (element.attribute(i).getName()
.equals(newElm.attribute(j).getName())) {
element.attribute(i).setValue(
newElm.attribute(j).getValue());
}
}
}
}
}
selectModifyXmlNode(element, elmOld, newElm);
}
}
/**
* 新建文件并添加内容
*
* @param filePathAndName
* 文件名称及地址 如:c:/test.txt
* @param fileContent
* 文件的内容
*/
public static void newFile(String filePathAndName, String fileContent) {
try {
String filePath = filePathAndName;
filePath = filePath.toString();
File myFilePath = new File(filePath);
if (!myFilePath.exists()) {
if (myFilePath.getParentFile().mkdirs()) {
myFilePath.createNewFile();
}
} else {
//如果存在就删除文件
// FileOperate.delFile(filePath);
myFilePath.delete();
}
FileWriter resultFile = new FileWriter(myFilePath);
PrintWriter myFile = new PrintWriter(resultFile);
String strCountent = fileContent;
myFile.println(strCountent);
resultFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 新建目录
* @param folderPath 如c:/f.txt
*/
public static void newFolder(String folderPath){
try {
String filePath = folderPath;
filePath = filePath.toString();
File myFilePath = new File(filePath);
if(!myFilePath.exists()){
myFilePath.mkdir();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除文件
* @param filePathAndName 文件路径及名称 如:C:/f.txt
* @return
*/
public static boolean delFile(String filePathAndName){
try {
String filePath = filePathAndName;
filePath = filePath.toString();
File myDelFile = new File(filePath);
return myDelFile.delete();
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除文件夹
* @param folderPath 文件夹的完整路径 如 c:/a
* @return
*/
public static boolean delFolder(String folderPath){
try {
delAllFile(folderPath);//删除里面的文件
String filePath = folderPath;
filePath = filePath.toString();
File myFilePath = new File(filePath);
return myFilePath.delete();
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除指定文件夹下的全部文件
* @param path
*/
public static void delAllFile(String path){
File file = new File(path);
if(!file.exists()){
return ;
}
if(!file.isDirectory()){
return ;
}
String[] tempList = file.list();
File temp = null;
for(int i=0; i<tempList.length;i++){
if(path.endsWith(file.separator)){
temp = new File(path + tempList[i]);
}else{
temp = new File(path + File.separator + tempList[i]);
}
if(temp.isFile()){
temp.delete();
}
if(temp.isDirectory()){
delAllFile(path + File.separator + tempList[i]);
delFolder(path + File.separator + tempList[i]);
}
}
}
/**
* 在文件中查找字符 所在的行
* @param filePath 文件的路径
* @param charName 要查找的字符
* @return
*/
public static int searchCharacter(String filePath,String charName){
BufferedReader inf;
int count = -1;
try {
inf = new BufferedReader(new FileReader(filePath));
String s = new String();
int findit = -1;
try {
while((s = inf.readLine()) != null && findit < 0){
findit = s.indexOf(charName);
count ++;
}
inf.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
return count;
}
/**
* 在文件的指定位置插入字符
* @param filePath 文件的路径
* @param insertCharName 将要插入的字符
* @param lineNumber 行号
*/
public static void insertCharacter(String filePath,String insertCharName, int lineNumber){
//临时文件
File outFile;
try {
outFile = File.createTempFile("name", ".tmp");
File inFile = new File(filePath);
//输入
FileInputStream fis = new FileInputStream(outFile);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
//输出
FileOutputStream fos = new FileOutputStream(outFile);
PrintWriter out = new PrintWriter(fos);
//保存一行数据
String thisLine;
//行号从 1 开始
int i= 1;
while((thisLine = in.readLine())!= null){
//如果行号等于目标行,则输出要插入的数据
if(i == lineNumber){
out.println(insertCharName);
}
//输出读取到的数据
out.println(thisLine);
//行号增加
i++;
}
out.flush();
out.close();
in.close();
//删除原始文件
inFile.delete();
//把临时文件改名为原文件名
outFile.renameTo(inFile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 拷贝文件
* @param oldPath 老的文件路径
* @param newPath 新的文件 路径
* @param override
*/
public static void copyFile(String oldPath,String newPath,boolean override){
File oldfile = new File(oldPath);
File df = new File(newPath);
//如果文件存在,且不进行覆盖,则直接返回
if(!override && df.exists()){
return ;
}
//如果目标路径不存在 ,则创建
File ppath = new File(df.getParent());
if(!ppath.exists()){
ppath.mkdirs();
}
if(oldfile.exists()){//文件存在时
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
inChannel = new FileInputStream(oldfile).getChannel();
outChannel = new FileOutputStream(df).getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(inChannel != null)
inChannel.close();
if(outChannel != null)
outChannel.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
}
/**
* 拷贝目录
* @param oldPath
* @param newPath
* @return
*/
public static void copyFolder(File oldPath,String newPath){
try {
(new File(newPath)).mkdirs(); //如果文件夹不存在,则建立新文件夹
String[] file = oldPath.list();
File temp = null;
for(int i=0;i<file.length;i++){
temp = new File(oldPath,file[i]);
if(temp.isFile()){
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + File.separator + (temp.getName()).toString());
byte[] b = new byte[1024 * 5];
int len;
while((len = input.read(b)) != -1){
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
if(temp.isDirectory()){//如果是子文件夹
copyFolder(new File(oldPath + File.separator + file[i]),newPath + File.separator + file[i]);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 取指定目录下的所有文件列表,包括子目录
* @param baseDir 指定的目录
* @return
*/
public static List<File> getSubFiles(File baseDir){
List<File> ret = new ArrayList<File>();
File[] tmp = baseDir.listFiles();
for(int i=0;i<tmp.length;i++){
if(tmp[i].isFile())
ret.add(tmp[i]);
if(tmp[i].isDirectory())
ret.addAll(getSubFiles(tmp[i]));
}
return ret;
}
/**
* 给定根目录,返回一个文件名对于该根目录的相对路径,用于zip文件中的路径
* @param baseDir 根目录
* @param realFileName 实际文件名
* @return
*/
public static String getAbsFileName(String baseDir,File realFileName){
if(baseDir.equals(realFileName.getAbsolutePath())){
return baseDir;
}
File real = realFileName;
File base = new File(baseDir);
String ret = real.getName();
while(true){
real = real.getParentFile();
if(real == null){
break;
}
if(real.equals(base)){
break;
}else{
ret = real.getName() + File.separator + ret;
}
}
return ret;
}
/**
* 缩压缩功能,将ZIP_FILENAME文件解压缩到ZIP_DIR目录下
* @param zipFile
* @param destDir
* @throws Exception
* @throws IOException
*/
public static void upZipFile(File zipFile,String destDir) throws Exception, IOException{
ZipFile zfile = new ZipFile(zipFile);
Enumeration<?> zList = zfile.entries();
ZipEntry ze = null;
byte[] buf = new byte[1024];
while(zList.hasMoreElements()){
ze = (ZipEntry)zList.nextElement();
if(ze.isDirectory()){
File f= new File(destDir + ze.getName());
f.mkdirs();
continue;
}
OutputStream os = new BufferedOutputStream(new FileOutputStream(getRealFileName(destDir,ze.getName())));
InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
int readLen = 0;
while((readLen = is.read(buf,0,1024))!= -1){
os.write(buf, 0, readLen);
}
is.close();
os.close();
}
zfile.close();
}
/**
* 拷贝全部文件到指定目录
* @param path
* @param dest
* @param pattern
* @param reversed
* @param override
*/
public static void copyAllFileTo(String path,String dest,String pattern,boolean reversed,boolean override){
File file = new File(path);
if(!file.exists()){
return ;
}
if(!file.isDirectory()){
return ;
}
String[] tempList = file.list();
File temp = null;
for(int i=0;i<tempList.length;i++){
if(path.endsWith(File.separator)){
temp = new File(path + temp);
}else{
temp = new File(path + File.separator + tempList[i]);
}
if(temp.isFile()){
String destf = dest + File.separator +temp.getName();
if(reversed && !temp.getName().matches(pattern)){
copyFile(temp.getAbsolutePath(), destf, override);
}else if(!reversed && temp.getName().matches(pattern)){
copyFile(temp.getAbsolutePath(), destf, override);
}
}
if(temp.isDirectory()){
copyAllFileTo(path + File.separator +tempList[i],dest,pattern,reversed,override);
}
}
}
}