1)字符串通用工具类 StringTools.java 的片段
import
java.io.BufferedReader;
import
java.io.BufferedWriter;
import
java.io.File;
import
java.io.FileReader;
import
java.io.FileWriter;
import
java.io.IOException;
import
java.text.SimpleDateFormat;
import
java.util.Calendar;
import
java.util.Date;
import
java.util.List;
public
class
StringTools {
/**
* 判断字符串不为空处理 如果是null or "" or "null" 返回false
*
*
@param
str
*
@return
*
@author
liutt
*/
public
static
boolean
notNull(String str) {
boolean
result
=
false
;
if
(str
!=
null
&&
!
str.equals(
""
)
&&
!
str.equals(
"
null
"
)) {
result
=
true
;
}
return
result;
}
/**
* 判断字符串为空
*
*
@param
str
*
@return
*
@author
liutt
*/
public
static
boolean
isNull(String str) {
boolean
result
=
notNull(str);
return
!
result;
}
public
static
boolean
isNull(List list) {
if
(list
==
null
||
list.isEmpty())
return
true
;
else
return
false
;
}
/**
* 在某月一号获得上月日期 "2006-05-01"转换为"2006-04"
*
*
@return
*/
public
static
String getLastMonthString() {
String lastdate
=
""
;
SimpleDateFormat formatter
=
new
SimpleDateFormat(
"
yyyy-MM-dd
"
);
String nowtime
=
getNowTime().substring(
0
,
10
);
//
getNowTime().substring(0,10);"2006-05-01";
//
"2006-05-01 12:01:20"
if
(StringTools.isNull(nowtime)
||
!
nowtime.substring(
8
,
10
).equals(
"
01
"
)) {
System.out.println(
"
null
"
);
return
null
;
}
Date date
=
(Date) java.sql.Date.valueOf(nowtime);
//
减去2天
java.util.Calendar cal
=
java.util.Calendar.getInstance();
cal.setTime(date);
cal.setTimeInMillis(cal.getTimeInMillis()
-
((
long
)
2
)
*
24
*
3600
*
1000
);
date
=
cal.getTime();
lastdate
=
(String) formatter.format(date);
//
日期去前5位
lastdate
=
lastdate.substring(
0
,
7
);
//
System.out.println(lastdate);
return
lastdate;
}
/**
* 将给定的字符串转换为UTF编码的字符串。
*
*
@param
str
* 输入字符串
*
@return
经UTF编码后的字符串,如果有异常,则返回原编码字符串
*/
public
static
String toUTF(String str) {
if
(isNull(str)) {
return
str;
}
String retVal
=
str;
try
{
retVal
=
new
String(str.getBytes(
"
ISO-8859-1
"
),
"
Unicode
"
);
//
ISO-8859-1
//
ISO8859_1
//
retVal = new String(str.getBytes("GBK"), "UTF-8");
//
retVal = new String(str.getBytes("ISO-8859-1"), "GBK");
//
retVal = new String(str.getBytes("UTF-8"), "GBK");
//
retVal = new String(str.getBytes("UTF-8"), "GB2312");
//
retVal = new String(str.getBytes("ISO-8859-1"), "GB2312");
//
retVal = new String(str.getBytes("GB2312"), "UTF-8");
}
catch
(Exception e) {
e.printStackTrace();
}
return
retVal;
}
/**
* 转换字符串:如("aa_a","a_","A")即将字符串"aa_a"中的"a_"转化为"A"
*
*
@param
source
*
@param
oldString
*
@param
newString
*
@return
*
*
@author
*/
public
static
String Replace(String source, String oldString,
String newString) {
StringBuffer output
=
new
StringBuffer();
int
lengthOfSource
=
source.length();
int
lengthOfOld
=
oldString.length();
int
posStart;
int
pos;
for
(posStart
=
0
; (pos
=
source.indexOf(oldString, posStart))
>=
0
; posStart
=
pos
+
lengthOfOld) {
output.append(source.substring(posStart, pos));
output.append(newString);
}
if
(posStart
<
lengthOfSource)
output.append(source.substring(posStart));
return
output.toString();
}
/**
* 字符串写到文件
*
*
@param
code
*
@param
filePath
*
@throws
IOException
*/
public
static
void
stringToFile(String code, String filePath)
throws
IOException {
if
(StringTools.notNull(code)) {
BufferedWriter out
=
new
BufferedWriter(
new
FileWriter(filePath));
out.write(code);
out.close();
}
}
/**
* 文件分行读转换为字符串
*
*
@param
filePath
*
@return
*
@throws
IOException
*/
public
static
String fileToString(String filePath)
throws
IOException {
String code
=
""
;
File newFile
=
new
File(filePath);
if
(newFile.exists()) {
BufferedReader br
=
new
BufferedReader(
new
FileReader(filePath));
String strLine;
StringBuffer strb
=
new
StringBuffer();
while
((strLine
=
br.readLine())
!=
null
) {
strb.append(strLine);
}
code
=
strb.toString();
}
return
code;
}
}
2)XML 通用工具类 XmlTools.java 的定义
import
java.io.BufferedWriter;
import
java.io.File;
import
java.io.FileWriter;
import
java.io.IOException;
import
java.util.logging.Logger;
import
org.dom4j.Document;
import
org.dom4j.DocumentException;
import
org.dom4j.DocumentHelper;
import
org.dom4j.Element;
import
org.dom4j.io.SAXReader;
import
org.dom4j.io.XMLWriter;
import
com.yourcompany.util.StringTools;
public
class
XmlTools {
private
static
final
Logger logger
=
Logger.getLogger(XmlTools.
class
.getName());
/**
* 从文件读取XML,返回XML文档
*
*
@param
filePath
*
@return
*
@throws
DocumentException
*/
public
static
Document read(String filePath)
throws
DocumentException {
SAXReader reader
=
new
SAXReader();
Document document
=
reader.read(
new
File(filePath));
return
document;
}
/**
* 创建XML
*
*
@return
*/
public
static
Document createDocument() {
Document document
=
DocumentHelper.createDocument();
//
document.addElement("root");
//
Element author1 =
//
root
//
.addElement(author)
//
.addAttribute(name, James)
//
.addAttribute(location, UK)
//
.addText(James Strachan);
//
Element author2 =
//
root
//
.addElement(author)
//
.addAttribute(name, Bob)
//
.addAttribute(location, US)
//
.addText(Bob McWhirter);
return
document;
}
/**
* 取得Root节点
*
*
@param
document
*
@return
*/
public
static
Element getRootElement(Document doc) {
return
doc.getRootElement();
}
/**
* 根据字符串文件获得根节点
*
*
@param
str
*
@return
*
@throws
DocumentException
*/
public
static
Element getRootElement(String str)
throws
DocumentException {
Element root
=
null
;
root
=
DocumentHelper.parseText(str).getRootElement();
return
root;
}
/**
* 简单输出
*/
public
static
void
writeSimply(Document document, String filePath)
throws
IOException {
FileWriter out
=
new
FileWriter(filePath);
document.write(out);
out.close();
}
/**
* 输出节点
*
*
@param
element
*
@param
filePath
* 文件路径全名
*
@throws
IOException
*/
public
static
void
writeElement(Element element, String filePath)
throws
IOException {
String oneXml
=
element.asXML();
BufferedWriter out
=
new
BufferedWriter(
new
FileWriter(filePath));
out.write(oneXml);
out.close();
}
/**
* xml输出 (用GB2312类型生成xml后,修改xml声明encoding="UTF-8" 为encoding="GB2312")
*
*
@param
document
*
@param
filePath
*
@throws
IOException
*/
public
static
void
write(Document document, String filePath)
throws
IOException {
//
指定文件
XMLWriter writer
=
new
XMLWriter(
new
FileWriter(filePath));
writer.write(document);
writer.close();
logger.info(
"
更新信息到xml文件:
"
+
filePath);
//
修改字符格式encoding="UTF-8" 为encoding="GB2312"
String newcode
=
StringTools.fileToString(filePath);
newcode
=
StringTools.Replace(newcode,
"
UTF-8
"
,
"
GB2312
"
);
StringTools.stringToFile(newcode, filePath);
}
/**
* 写到xml文件
*
*
@param
document
*
@param
filePath
*
@throws
IOException
*/
public
static
void
writeToXml(Document document, String filePath)
throws
IOException {
String oneXml
=
document.asXML();
//
logger.info(oneXml);
//
oneXml=StringTools.toUTF(oneXml);
//
logger.info(oneXml);
BufferedWriter out
=
new
BufferedWriter(
new
FileWriter(filePath));
out.write(oneXml);
out.close();
}
/**
*
@param
args
*/
public
static
void
main(String[] args) {
//
TODO 自动生成方法存根
logger.info(
""
);
}
}
3)把 List 数据写入 XML
public
static
void
main(String[] args) {
Document document
=
XmlTools.createDocument();
/*
Element catalogElement = document.addElement("catalog");
catalogElement.addComment("An XML Catalog");
Element journalElement = catalogElement.addElement("journal");
journalElement.addAttribute("title", "特利堡");
journalElement.addAttribute("name", "我的朋友");
journalElement.setText("testtest");
*/
Element rootElement
=
document.addElement(
"
root
"
);
Element titleElement
=
rootElement.addElement(
"
title
"
);
titleElement.setText(
"
排行榜
"
);
Element hittingElement
=
rootElement.addElement(
"
hitting
"
);
Element row,index,name,score,detail;
row
=
hittingElement.addElement(
"
r
"
);
index
=
row.addElement(
"
i
"
);
name
=
row.addElement(
"
n
"
);
score
=
row.addElement(
"
s
"
);
detail
=
row.addElement(
"
d
"
);
index.setText(
"
排名
"
);
name.setText(
"
用户
"
);
score.setText(
"
积分
"
);
detail.setText(
"
详细
"
);
for
(
int
i
=
1
;i
<=
10
;i
++
){
row
=
hittingElement.addElement(
"
r
"
);
index
=
row.addElement(
"
i
"
);
name
=
row.addElement(
"
n
"
);
score
=
row.addElement(
"
s
"
);
detail
=
row.addElement(
"
d
"
);
index.setText(String.valueOf(i));
name.setText(
"
第
"
+
String.valueOf(i)
+
"
名
"
);
score.setText(String.valueOf(i
*
1000
));
detail.setText(String.valueOf(
900
+
i));
}
try
{
String filepath
=
"
F:\\XmlTest\\catalog.xml
"
;
XmlTools.write(document, filepath);
}
catch
(IOException e) {
System.out.println(e.getMessage());
}
}