我一个项目中用到的,里面的方法不是太通用,但是可以从里面找到一些有用的代码,以后慢慢添补更新:

FileUtil.xml

 package com.novel.util;

 import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; /**
* @author cy
*
* @date 2015年7月24日 上午8:38:38
*
* @Description 关于文件的一些工具
*/
public class FileUtils {
/**
* 将文件中所有内容读取到字符串中
*
* @param filePath
* 文件路径
* @return 文件内容
*/
public static String getStringFromFile(String filePath) {
File file = new File(filePath) ;
if(!file.exists()){
return "" ;
}
/**
* 处理文件读取乱码问题 :
* 只要判定两种常见的编码就可以了:GBK和UTF-8。由于中文Windows默认的编码是GBK,所以一般只要判定UTF-8编码格式。
*对于UTF-8编码格式的文本文件,其前3个字节的值就是-17、-69、-65
*/
try{
byte[] firstThreeByte = new byte[3] ;
InputStream in = new FileInputStream(file) ;
in.read(firstThreeByte) ;
in.close() ;
String encoding = "" ;
if(firstThreeByte[0] == -17 && firstThreeByte[1] == -16 && firstThreeByte[2] == -65){
encoding = "utf-8" ;
}else{
encoding = "gbk" ;
}
InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding);
Long filelength = file.length() / 2 ; // 该方法获取的是文件字节长度,
//而我要创建的是char数组,char占两个字节,
//byte一个字节,所以除以2表示的是该文件的字符长度
char[] filecontent = new char[filelength.intValue()] ;
read.read(filecontent) ;
return new String(filecontent) ;
}catch(Exception e ){
e.printStackTrace();
return "" ;
}
} /**
* 将字符串写入文件
*
* @param content
* 字符串内容
* @param filePath
* 文件路径
* @throws IOException
*/
public static void writeStringToFile(String content, String filePath)
throws IOException { File file = new File(filePath);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream out = new FileOutputStream(file);
out.write(content.getBytes());
out.close();
}
/**
* 删除指定的文件
* @param filePath文件路径
*/
public static void deleteFile(String filePath ) {
File file = new File(filePath) ;
if(file.exists()){
file.delete() ;
}
}
}

XmlUtil.java

 package com.novel.util;

 import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException; import com.novel.entity.Novel;
import com.novel.entity.User; /**
* @author cy
*
* @date 2015年7月23日 下午3:19:06
*
* @Description 关于xml的操作
*/
public class XmlUtil {
/**
* 目标xml为 config/users.xml
*
* @param user
* 将要被写入xml的User对象
* @return 是否成功
*/
public static boolean writeUserToXml(User user) {
try {
Document doc = getDocumentFromXml("config/users.xml");
Element newUserElement = doc.createElement("user");
Element newUsernameElement = doc.createElement("name");
Text nameTextNode = doc.createTextNode("nameValue");
nameTextNode.setNodeValue(user.getName());
newUsernameElement.appendChild(nameTextNode);
Element newUserPwdElement = doc.createElement("pwd");
Text pwdTextNode = doc.createTextNode("pwdValue");
pwdTextNode.setNodeValue(user.getName());
newUserPwdElement.appendChild(pwdTextNode);
newUserElement.appendChild(newUsernameElement);
newUserElement.appendChild(newUserPwdElement);
Element usersElement = (Element) doc.getElementsByTagName("users")
.item(0);
usersElement.appendChild(newUserElement); writeDocumentToFile(doc, "config/users.xml");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
*
* @param doc
* XML中的Document对象
* @param filePath
* 输出的文件路径
* @throws TransformerFactoryConfigurationError
* @throws TransformerConfigurationException
* @throws TransformerException
*/
private static void writeDocumentToFile(Document doc, String filePath)
throws TransformerFactoryConfigurationError,
TransformerConfigurationException, TransformerException {
// 写入到硬盘
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
/** 编码 */
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filePath));
transformer.transform(source, result);
} /**
* 加载config/users.xml中用户信息到对象中
*
* @return 加载后的对象
*/
public static Map<String, User> initUser() {
InitUser.users = new HashMap<String, User>();
try {
Document doc = getDocumentFromXml("config/users.xml");
NodeList usersNodeList = doc.getElementsByTagName("user");
for (int i = 0; i < usersNodeList.getLength(); i++) {
Element userElement = (Element) usersNodeList.item(i);
String userName = ((Element) (userElement
.getElementsByTagName("name").item(0))).getFirstChild()
.getNodeValue();
String passwd = ((Element) (userElement
.getElementsByTagName("pwd").item(0))).getFirstChild()
.getNodeValue();
InitUser.users.put(userName, new User(userName, passwd));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
return InitUser.users;
}
} /**
* 从xml中获取服务器运行的端口
*
* @return server.xml文件中的端口号
*/
public static int getServerPort() {
try {
Document doc = getDocumentFromXml("config/server.xml");
int serverPort = Integer.parseInt(doc
.getElementsByTagName("server-port").item(0)
.getFirstChild().getNodeValue());
return serverPort;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
} /**
*
* @param xmlPath
* xml文件的位置
* @return 这个xml文件相应的Document对象
* @throws SAXException
* @throws IOException
* @throws ParserConfigurationException
*/
public static Document getDocumentFromXml(String xmlPath)
throws SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlPath);
return doc;
} /**
* 读取xml中小说的信息到List中
*
* @param novelId
* 小说id
* @return 小说列表
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
public static List<Novel> getNovelListFromXml(String filePath) throws SAXException, IOException, ParserConfigurationException {
List<Novel> novelList = new ArrayList<Novel>();
Document doc = getDocumentFromXml(filePath);
NodeList novels = doc.getElementsByTagName("novel");
for (int i = 0; i < novels.getLength(); i++) {
Element novel = ((Element) novels.item(i));
int id = Integer.parseInt(novel.getElementsByTagName("id").item(0)
.getFirstChild().getNodeValue());
String name = novel.getElementsByTagName("name").item(0)
.getFirstChild().getNodeValue();
String author = novel.getElementsByTagName("author").item(0)
.getFirstChild().getNodeValue();
String category = novel.getElementsByTagName("category").item(0)
.getFirstChild().getNodeValue();
String description = novel.getElementsByTagName("description")
.item(0).getFirstChild().getNodeValue(); Novel oneNovel = new Novel(id, category, name, author, description);
novelList.add(oneNovel);
}
return novelList ;
}
/**
* 将Novel信息写入到config/novelsInfo.xml中并且将小说内容写入到novel文件夹下
* @param novel 小说对象
* @return 是否写入成功
* TODO:确定原子操作
*/
public static boolean writeNovelToFile(Novel novel ) {
/**
* 先将小说内容写入到novel文件夹下,再将小说信息写入到config/novelsInfo.xml中
*/
try{
FileUtils.writeStringToFile(novel.getContent(), "novel/" + novel.getName() + ".txt");
XmlUtil.writeNovelInfoToXml(novel) ;
return true ;
}catch(Exception e ){
/**
* 如果写入小说到文件中出现问题,要将已经写入的信息删除
* 这段代码应该很少执行到 ~~~~
*
*/
System.out.println("小说写入文件失败,正在回滚~~");
FileUtils.deleteFile("novel/" + novel.getName() + ".txt") ;
XmlUtil.deleteNovelInfoFromXml(novel) ;
e.printStackTrace();
return false ;
}
} /**
* 从config/novelsInfo.xml中删除与novel对象相对应的的novel标签,根据ID号判断是否相同
*
* @param novel
* 小说对象
*/
public static void deleteNovelInfoFromXml(Novel novel) {
try {
Document doc = getDocumentFromXml("config/novelsInfo.xml");
Element novelsElement = (Element) doc
.getElementsByTagName("novels").item(0);
NodeList novelElements = novelsElement
.getElementsByTagName("novel"); Node deleteElement = null;
for (int i = 0; i < novelElements.getLength(); i++) {
String id = ((Element) novelElements.item(i))
.getElementsByTagName("id").item(0).getFirstChild()
.getNodeValue();
if (id.equals(String.valueOf(novel.getId()))) {
deleteElement = novelElements.item(i);
break;
}
}
novelsElement.removeChild(deleteElement);
writeDocumentToFile(doc, "config/novlesInfo.xml");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将小说信息写入到config/novelsInfo.xml文件中
* @param novel小说对象
*/
public static void writeNovelInfoToXml(Novel novel){
Document doc = null ;
try {
doc = getDocumentFromXml("config/novelsInfo.xml");
} catch (Exception e) {
e.printStackTrace();
return ;
}
Element novelDocument = (Element)doc.createElement("novel") ;
// id
Element novelIdDocument = (Element)doc.createElement("id") ;
Text novelIdTextNode = doc.createTextNode("idValue") ;
novelIdTextNode.setNodeValue(String.valueOf(novel.getId()));
novelIdDocument.appendChild(novelIdTextNode);
// name
Element novelNameDocument = (Element)doc.createElement("name") ;
Text novelNameTextNode = doc.createTextNode("nameValue") ;
novelNameTextNode.setNodeValue(String.valueOf(novel.getName()));
novelNameDocument.appendChild(novelNameTextNode);
// author
Element novelAuthorDocument = (Element)doc.createElement("author") ;
Text novelAuthorTextNode = doc.createTextNode("authorValue") ;
novelAuthorTextNode.setNodeValue(String.valueOf(novel.getAuthor()));
novelAuthorDocument.appendChild(novelAuthorTextNode);
// category
Element novelCategoryDocument = (Element)doc.createElement("category") ;
Text novelCategoryTextNode = doc.createTextNode("categoryValue") ;
novelCategoryTextNode.setNodeValue(String.valueOf(novel.getCategory()));
novelCategoryDocument.appendChild(novelCategoryTextNode);
// description
Element novelDescriptionDocument = (Element)doc.createElement("description") ;
Text novelDescriptionTextNode = doc.createTextNode("descriptionValue") ;
novelDescriptionTextNode.setNodeValue(String.valueOf(novel.getDescription()));
novelDescriptionDocument.appendChild(novelDescriptionTextNode); novelDocument.appendChild(novelIdDocument) ;
novelDocument.appendChild(novelNameDocument) ;
novelDocument.appendChild(novelAuthorDocument) ;
novelDocument.appendChild(novelCategoryDocument) ;
novelDocument.appendChild(novelDescriptionDocument) ;
doc.getElementsByTagName("novels").item(0).appendChild(novelDocument) ;
// 写到文件中
try {
writeDocumentToFile(doc, "config/novelsInfo.xml");
} catch (Exception e) {
e.printStackTrace();
}
}
}

xml、文件操作功能类的更多相关文章

  1. xml文件操作帮助类

    xml文件的节点值获取和节点值设置 /// <summary> /// 保存单个点节点的值 /// </summary> /// <param name="Up ...

  2. SpringBatch Sample (三)(XML文件操作)

    前篇关于Spring Batch的文章,讲述了Spring Batch 对CSV文件的读写操作. 本文将通过一个完整的实例,与大家一起讨论运用Spring Batch对XML文件的读写操作.实例流程是 ...

  3. ASP.NET MVC 学习笔记-2.Razor语法 ASP.NET MVC 学习笔记-1.ASP.NET MVC 基础 反射的具体应用 策略模式的具体应用 责任链模式的具体应用 ServiceStack.Redis订阅发布服务的调用 C#读取XML文件的基类实现

    ASP.NET MVC 学习笔记-2.Razor语法   1.         表达式 表达式必须跟在“@”符号之后, 2.         代码块 代码块必须位于“@{}”中,并且每行代码必须以“: ...

  4. C#读取XML文件的基类实现

    刚到新单位,学习他们的源代码,代码里读写系统配置文件的XML代码比较老套,直接写在一个系统配置类里,没有进行类的拆分,造成类很庞大,同时,操作XML的读写操作都是使用SetAttribute和node ...

  5. C# XML文件操作

    C# XML文件操作 运行环境:Window7 64bit,.NetFramework4.61,C# 6.0: 编者:乌龙哈里 2017-02-09 参考 LINQ to XML System.Xml ...

  6. XML文件与实体类的互相转换

    XML文件与实体类的互相转换 一.将XML文件反序列化为实体类对象 1. 通常程序的配置信息都保存在程序或者网站的专门的配置文件中(App.config/web.config).但是现在为了演示XML ...

  7. 我来讲讲在c#中怎么进行xml文件操作吧,主要是讲解增删改查!

    我把我写的四种方法代码贴上来吧,照着写没啥问题. 注: <bookstore> <book> <Id>1</Id> <tate>2010-1 ...

  8. PHP文件操作功能函数大全

    PHP文件操作功能函数大全 <?php /* 转换字节大小 */ function transByte($size){ $arr=array("B","KB&quo ...

  9. 如何在Mybatis的xml文件调用java类的方法

    在mybatis的映射xml文件调用java类的方法:使用的是OGNL表达式,表达式格式为:${@prefix@methodName(传递参数名称)} 1.如下代码所示:方法必须为静态方法:以下我只是 ...

随机推荐

  1. 通过PHP扩展phpredis操作redis

    我们使用phpredis,这个扩展能让你用PHP操作redis. 源码下载: phpize ./configure ); var_dump($result); echo $redis->get( ...

  2. loopback 05

    数据并发处理 数据库事务 事务隔离 ACID性质 原子性(Atomicity): 要么全部被执行,要么都不执行; 一致性(Consistency): 满足完整性约束; 隔离性(Isolation): ...

  3. 插入视频(youtube)

    iframe 如果没有flash播放器,会自动使用html5播放器 <iframe width="420" height="315" src=" ...

  4. 20145223《Java程序设计》第6周学习总结

    20145223 <Java程序设计>第6周学习总结 教材学习内容总结 ·Java中将数据从来源取出或是将数据写入目的地,使用输入.输出串流,其分别的代表对象为java.io.InputS ...

  5. http://chenzhou123520.iteye.com/blog/1811340

    http://chenzhou123520.iteye.com/blog/1811340

  6. nginx实现ssl反向代理实战

    登录认证account.free4lab.com需要提供ssl登录接口,ssl的原理看这篇博文,因为前面有反向代理nginx,所以这个需求就放在nginx实现了,否则可以放在web容器(jetty,t ...

  7. three.js 显示一条线

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  8. 关于ui修改的若干想法

    1.现在发现统一规划好各种xml资源.图片资源还是很重要的. 为什么?因为,很多一些ui设计,比如标题.文字大小.列表的宽高都是统一的, 据我个人理解,一个ui多个部分,如果很多部分都是设计上统一的, ...

  9. shinydashboard包---为shiny提供BI框架

    1.安装 install.packages("shinydashboard") 2.基础知识 仪表盘有三个部分:标题.侧边栏,身体.下面是最最小的仪表面板页面的UI: ## ui. ...

  10. [转]error while loading shared libraries 错误解决办法总结

    http://blog.csdn.net/wallwind/article/details/7580659 错误信息: error while loading shared libraries: li ...