效果:
一.准备XML
sam
111111
nanana
234567
老干爹
222222
jack
111111
老干妈
1234556
二.一个联系人实体类
sam
111111
nanana
234567
老干爹
222222
jack
111111
老干妈
1234556
三.程序入口
package cn.hncu.xml.contact;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
/**
* dos版
* 对contacts.xml进行添删改查
*
* 菜单:
* 1.登录
* 2.注册
* 0.退出
* 登录成功后的菜单:
* 1.查找所有联系人
* 2.添加一个联系人
* 3.修改一个联系人
* 4.删除一个联系人
* 0.退出
* @author BarryLee
* @2018年8月21日@上午9:23:56
*/
public class Main {
public static Document dom = null;
public static Element root = null;
public static Element curUser = null;//当前用户
public static Scanner sc = new Scanner(System.in);
public static final String fileName = "./xmls/contacts.xml";
private static Service service = new Service();
public static void main(String[] args) {
System.out.println("******欢迎使用******");
while(true) {
printMenu1();
String n = sc.next();
switch (n) {
case "1"://登录
if(service.loginService()) {
System.out.println("登录成功");
loginSuccess();
}else {
System.out.println("登录失败");
}
System.out.println();
break;
case "2"://注册
if(service.registerService()) {
System.out.println("注册成功");
}else {
System.out.println("注册失败");
}
System.out.println();
break;
case "0"://退出系统
return;
default:
System.out.println("请输入正确的指令");
System.out.println();
}
}
}
public static void loginSuccess() {
while(true) {
printMenu2();
String n = sc.next();
switch (n) {
case "1"://查找所有联系人
List list = service.getMyContactsService();
Utils.printContact(list);
break;
case "2"://添加一个联系人
if(service.addContactService()) {
System.out.println("添加成功");
}else {
System.out.println("添加失败");
}
System.out.println();
break;
case "3"://修改一个联系人
service.getMyContacts();
if(service.modContactService()) {
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
System.out.println();
break;
case "4"://删除一个联系人
if(service.delContactService()) {
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
System.out.println();
break;
case "0"://退出登录
curUser = null;
return ;
default:
System.out.println("请输入正确的指令");
}
}
}
public static void printMenu1() {
System.out.println();
System.out.println("请输入命令:");
System.out.println("1.登录,2.注册,0.退出");
System.out.print("->");
}
public static void printMenu2() {
System.out.println();
System.out.println("请输入命令:");
System.out.println("1.查看所有联系人,2.添加一个联系人");
System.out.println("3.修改一个联系人,4.删除一个联系人");
System.out.println("0.退出登录");
System.out.print("->");
}
static {
try {
//保证只有一个dom
dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(fileName);
root = (Element)dom.getFirstChild();
} catch (SAXException | IOException | ParserConfigurationException e) {
//e.printStackTrace();
}
}
}
四.Service层
package cn.hncu.xml.contact;
import java.util.List;
import java.util.Scanner;
public class Service {
private Dao dao = new Dao();
private Scanner sc = new Scanner(System.in);
/**
* 登录
* @return
*/
public boolean loginService() {
String[] user = getNamePwd();
if (user != null) {
return dao.login(user[0], user[1]);
}
return false;
}
/**
* 注册
* @return
*/
public boolean registerService() {
String[] user = getNamePwd();
if (user != null) {
return dao.register(user[0], user[1]);
}
return false;
}
/**
* 获取用户名和密码 返回空时:输入错误 不为空时:[0]为用户名,[1]为密码
* @return
*/
public String[] getNamePwd() {
// 用户名不允许空格,密码允许空格
System.out.print("请输入用户名:");
String name = sc.next();
if (name == null || name.trim().length() == 0) {
System.out.println("用户名不能为空");
return null;
}
System.out.print("请输入用户密码:");
String pwd = sc.next();
if (pwd == null || pwd.length() == 0) {
System.out.println("密码不能为空");
return null;
}
return new String[] { name, pwd };
}
public String[] getNamePhone() {
System.out.println("请输入用户名");
String name = sc.next();
if (name == null || name.trim().length() == 0) {
System.out.println("用户名不能为空");
return null;
}
System.out.println("请输入电话号码");
String phone = sc.next();
if (phone == null || phone.trim().length() == 0) {
System.out.println("手机号不能为空");
return null;
}
return new String[] { name, phone };
}
public List getMyContactsService() {
return getMyContacts();
}
public boolean addContactService() {
String res[] = getNamePhone();
if (res == null) {
return false;
}
return dao.addContact(new Contact(res[0], res[1]));
}
public boolean modContactService() {
System.out.print("请输入要修改的联系人的id->");
int i = -1;
try {
i = Integer.parseInt(sc.next());
if (i > 0 && i <= getMyContacts().size()) {
String res[] = getNamePhone();
if (res == null) {
return false;
}
Contact contact = new Contact(res[0], res[1]);
return dao.modContact(i - 1, contact);
}
} catch (NumberFormatException e) {
//e.printStackTrace();
}
return false;
}
public boolean delContactService() {
int i = -1;
System.out.print("请输入要删除联系人的id->");
try {
i = Integer.parseInt(sc.next());
if (i > 0 && i <= getMyContacts().size()) {
return dao.delContact(i-1);
}
} catch (NumberFormatException e) {
//e.printStackTrace();
}
return false;
}
public List getMyContacts() {
return dao.getMyContacts();
}
}
五.DAO层
package cn.hncu.xml.contact;
import java.util.ArrayList;
import java.util.List;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactoryConfigurationError;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class Dao {
/**
* 根据用户名和密码进行登录
*
* @param name
* @param pwd
*/
public boolean login(String name, String pwd) {
try {
NodeList list = Main.root.getElementsByTagName("user");
// 遍历所有用户
for (int i = 0; i < list.getLength(); i++) {
String getName = ((Element) list.item(i)).getElementsByTagName("name").item(0).getTextContent();
String getPwd = ((Element) list.item(i)).getElementsByTagName("password").item(0).getTextContent();
if (getName.equals(name) && getPwd.equals(pwd)) {
// 设置当前用户
Main.curUser = (Element) (list.item(i));
return true;// 找到
}
}
} catch (Exception e) {
//e.printStackTrace();
}
return false;
}
/**
* 用户注册
*
* @param name
* @param pwd
* @return
*/
public boolean register(String name, String pwd) {
try {
// 创建用户节点
Element eUser = Main.dom.createElement("user");
Element eName = Main.dom.createElement("name");
eName.setTextContent(name);
Element ePwd = Main.dom.createElement("password");
ePwd.setTextContent(pwd);
Element eCon = Main.dom.createElement("contacts");
// 添加到dom中
eUser.appendChild(eName);
eUser.appendChild(ePwd);
eUser.appendChild(eCon);
Main.root.appendChild(eUser);
// 持久化
return Utils.save(Main.dom);
} catch (Exception e) {
//e.printStackTrace();
}
return false;
}
/**
* 找到当前用户的所有联系人
*
* @return
*/
public List getMyContacts() {
List list = new ArrayList<>();
try {
if (Main.curUser == null)
return list;// 防范
Element eCs = (Element) Main.curUser.getElementsByTagName("contacts").item(0);
NodeList conList = eCs.getElementsByTagName("contact");// 获取到了当前用户的所有联系人
for (int i = 0; i < conList.getLength(); i++) {
// 获取用户名和手机号
String name = ((Element) conList.item(i)).getElementsByTagName("name").item(0).getTextContent();
String phone = ((Element) conList.item(i)).getElementsByTagName("phone").item(0).getTextContent();
list.add(new Contact(name, phone));
}
} catch (Exception e) {
//e.printStackTrace();
}
return list;
}
/**
* 为当前用户添加一个联系人
*
* @param contact
* @return
*/
public boolean addContact(Contact contact) {
try {
if (Main.curUser == null)
return false;
// 创建联系人节点
Element eCon = Main.dom.createElement("contact");
Element eName = Main.dom.createElement("name");
eName.setTextContent(contact.getName());
Element ePhone = Main.dom.createElement("phone");
ePhone.setTextContent(contact.getPhone());
// 找到当前用户的contacts节点
Element eCons = (Element) Main.curUser.getElementsByTagName("contacts").item(0);
// 添加到dom中
eCon.appendChild(eName);
eCon.appendChild(ePhone);
eCons.appendChild(eCon);
// 持久化
return Utils.save(Main.dom);
} catch (Exception e) {
//e.printStackTrace();
}
return false;
}
/**
* 根据是第几个孩子进行删除联系人
*
* @param i
* @return
*/
public boolean delContact(int i) {
if (Main.curUser == null)
return false;
Element eCons = (Element) (Main.curUser.getElementsByTagName("contacts")).item(0);
Element eConi = (Element) (eCons.getElementsByTagName("contact")).item(i);
System.out.println("eConi:"+eConi);
System.out.println("eConiP:"+eConi.getParentNode());
eConi.getParentNode().removeChild(eConi);
try {
Utils.save(Main.dom);
return true;
} catch (TransformerFactoryConfigurationError | TransformerException e) {
//e.printStackTrace();
}
return false;
}
/**
* 修改当前联系人的指定某个联系人进行修改操作
*
* @param contact
* @return
*/
public boolean modContact(int i, Contact contact) {
if (Main.curUser == null)
return false;
// contacts
Element eCons = (Element) ((Main.curUser.getElementsByTagName("contacts")).item(0));
Element eConi = (Element) ((eCons.getElementsByTagName("contact")).item(i));
eConi.getElementsByTagName("name").item(0).setTextContent(contact.getName());
eConi.getElementsByTagName("phone").item(0).setTextContent(contact.getPhone());
try {
Utils.save(Main.dom);
return true;
} catch (TransformerFactoryConfigurationError | TransformerException e) {
//e.printStackTrace();
}
return false;
}
}
六.工具类
package cn.hncu.xml.contact;
import java.io.File;
import java.util.List;
import javax.xml.transform.Transformer;
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;
public class Utils {
public static boolean save(Document dom) throws TransformerFactoryConfigurationError, TransformerException {
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.transform(new DOMSource(dom), new StreamResult(new File(Main.fileName)));
return true;
}
/**
* 打印当前用户的所有联系人,id从1开始
* @param list
*/
public static void printContact(List list) {
if (list.size() == 0) {
System.out.println("没有任何信息");
} else {
for(int i = 1;i<=list.size();i++) {
System.out.println("id: "+i+", "+list.get(i-1));
}
}
}
}