자바 코드 xml 파일 추가 삭제 검사 작업

6968 단어
1. 자바 프로젝트 를 만 들 고 dom4j - 1.6.1. jar 를 도입 합 니 다.
2. 자바 프로젝트 에서 xml 문 서 를 정의 합 니 다. student. xml 이 라 고 부 르 고 conf 폴 더 에 놓 습 니 다.
       초기 내용 은 다음 과 같 습 니 다. (students 의 루트 태그 포함)



3. student 클래스 정의, 이름, 나이 포함, 남학생 여부 세 가지 속성

package fileoperation;

public class Student {
	private String name;
	private int age;
	private boolean isBoy;
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public int getAge() {
		return age;
	}
	
	public void setAge(int age) {
		this.age = age;
	}
	
	public boolean isBoy() {
		return isBoy;
	}
	
	public void setBoy(boolean isBoy) {
		this.isBoy = isBoy;
	}
	
	@Override
	public String toString() {
		return "student [name=" + name + ", age=" + age + ", isBoy=" + isBoy + "]";
	}
}

4. xml 파일 을 추가 삭제 하고 검사 하 는 클래스 를 정의 합 니 다.

package fileoperation;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class Operation {
	private static String FILE_PATH = "conf/student.xml";     //    

        // xml           
	public static void addStudent(Student student)
	{
		InputStream in = null;
		SAXReader reader = new SAXReader();
		Document doc = null;
		try
		{
			in = new FileInputStream(FILE_PATH);
			System.out.println(in);
			doc = reader.read(in);
			Element root = doc.getRootElement();   //  xml   , students  
			Element element = root.addElement("student");
			element.addElement("name").addText(student.getName());
			element.addElement("age").addText(String.valueOf(student.getAge()));
			element.addElement("isBoy").addText(String.valueOf(student.isBoy()));

			XMLWriter writer = new XMLWriter();
			FileOutputStream fos = new FileOutputStream(FILE_PATH);
			System.out.println(fos);
			writer.setOutputStream(fos);
			writer.write(doc);
			writer.close();
		}
		catch (Exception e)
		{
			System.out.println("error");
		}
		finally
		{
			try
			{
			
				if(in != null)
					in.close();
			}
			catch (IOException e)
			{
				System.out.println("error");
			}
		}
	}

        //      ,                
	public static void updateStudent(Student student)
	{
		InputStream in = null;
		SAXReader reader = new SAXReader();
		Document doc = null;
		try
		{
			in = new FileInputStream(FILE_PATH);
			doc = reader.read(in);
			Element root = doc.getRootElement();
			for (Iterator it = root.elementIterator(); it.hasNext();)
			{
				Element element = (Element) it.next();
				if (student.getName().equals(element.element("name").getText()))
				{
					element.element("age").setText(String.valueOf(student.getAge()));
					element.element("isBoy").setText(String.valueOf(student.isBoy()));
					break;
				}
			}
			FileWriter writer = new FileWriter(FILE_PATH);
			doc.write(writer);
			writer.flush();
			writer.close();
		}
		catch (Exception e)
		{
			System.out.println("error");
		}
		finally
		{
			try
			{
				in.close();
			}
			catch (IOException e)
			{
				System.out.println("error");
			}
		}
	}

        //  xml       
	public static List getStudents()
	{
		InputStream in = null;
		SAXReader reader = new SAXReader();
		Document doc = null;
		List Students = new ArrayList<>();
		try
		{
			in = new FileInputStream(FILE_PATH);
			doc = reader.read(in);
			Element root = doc.getRootElement();
			List elements = root.elements();
			Students = new ArrayList();
			for (Element element : elements)
			{
				Student student = new Student();
				student.setName(element.elementText("name"));
				student.setAge(Integer.valueOf(element.elementText("age")));
				student.setBoy(Boolean.valueOf(element.elementText("isBoy")));
				Students.add(student);
			}
		}
		catch (Exception e1)
		{
			System.out.println("error");
		}
		finally
		{
			try
			{
				in.close();
			}
			catch (IOException e)
			{
				System.out.println("error");
			}
		}

		return Students;
	}
	
        //           xml 
	public static boolean studentIsExist(String name) 
	{
		InputStream in = null;
		SAXReader reader = new SAXReader();
		Document doc = null;
		
		try {
			in = new FileInputStream(FILE_PATH);
			doc = reader.read(in);
			Element root = doc.getRootElement();
			List elements = root.elements();
			for (Element element : elements)
			{
				if(name != null && name.equals(element.elementText("name")))
					return true;
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return false;
	}
	
        //  xml          ,      xml  
	public static boolean deleteAllStudents()
	{
		InputStream in = null;
		SAXReader reader = new SAXReader();
		Document doc = null;
		
		try {
			in = new FileInputStream(FILE_PATH);
			doc = reader.read(in);
			Element root = doc.getRootElement();
			List elements = root.elements();
			for(Element element : elements)
			{
				element.detach();
			}
			FileWriter writer = new FileWriter(FILE_PATH);
			doc.write(writer);
			writer.flush();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return false;
	}
	
        //  xml        
	public static boolean deleteStudent(String name)
	{
		InputStream in = null;
		SAXReader reader = new SAXReader();
		Document doc = null;
		
		try {
			in = new FileInputStream(FILE_PATH);
			doc = reader.read(in);
			Element root = doc.getRootElement();
			List elements = root.elements();
			for(Element element : elements)
			{
				if(name != null && name.equals(element.elementText("name")))
					element.detach();
			}
			FileWriter writer = new FileWriter(FILE_PATH);
			doc.write(writer);
			writer.flush();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return false;
	}
	
}

좋은 웹페이지 즐겨찾기