백엔드 개발 XML/RSS 튜토리얼 xml, 파일 연산 함수 클래스의 샘플 코드에 대한 자세한 설명

xml, 파일 연산 함수 클래스의 샘플 코드에 대한 자세한 설명

Mar 22, 2017 pm 04:33 PM

프로젝트에서 사용했는데, 그 안에 있는 메서드가 그다지 보편적이지는 않지만, 앞으로 천천히 추가하고 업데이트하겠습니다.

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, 파일 연산 함수 클래스의 샘플 코드에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

PowerPoint를 사용하여 XML 파일을 열 수 있나요? PowerPoint를 사용하여 XML 파일을 열 수 있나요? Feb 19, 2024 pm 09:06 PM

XML 파일을 PPT로 열 수 있나요? XML, Extensible Markup Language(Extensible Markup Language)는 데이터 교환 및 데이터 저장에 널리 사용되는 범용 마크업 언어입니다. HTML에 비해 XML은 더 유연하고 자체 태그와 데이터 구조를 정의할 수 있으므로 데이터 저장과 교환이 더 편리하고 통합됩니다. PPT 또는 PowerPoint는 프레젠테이션 작성을 위해 Microsoft에서 개발한 소프트웨어입니다. 이는 포괄적인 방법을 제공합니다.

Golang을 사용하여 파일을 안전하게 읽고 쓰는 방법은 무엇입니까? Golang을 사용하여 파일을 안전하게 읽고 쓰는 방법은 무엇입니까? Jun 06, 2024 pm 05:14 PM

Go에서는 안전하게 파일을 읽고 쓰는 것이 중요합니다. 지침은 다음과 같습니다. 파일 권한 확인 지연을 사용하여 파일 닫기 파일 경로 유효성 검사 컨텍스트 시간 초과 사용 다음 지침을 따르면 데이터 보안과 애플리케이션의 견고성이 보장됩니다.

Python에서 XML 데이터를 CSV 형식으로 변환 Python에서 XML 데이터를 CSV 형식으로 변환 Aug 11, 2023 pm 07:41 PM

Python의 XML 데이터를 CSV 형식으로 변환 XML(ExtensibleMarkupLanguage)은 데이터 저장 및 전송에 일반적으로 사용되는 확장 가능한 마크업 언어입니다. CSV(CommaSeparatedValues)는 데이터 가져오기 및 내보내기에 일반적으로 사용되는 쉼표로 구분된 텍스트 파일 형식입니다. 데이터를 처리할 때, 간편한 분석과 처리를 위해 XML 데이터를 CSV 형식으로 변환해야 하는 경우가 있습니다. 파이썬은 강력하다

gho 파일을 삭제할 수 있나요? gho 파일을 삭제할 수 있나요? Feb 19, 2024 am 11:30 AM

gho 파일은 NortonGhost 소프트웨어로 생성된 이미지 파일이며 운영 체제와 데이터를 백업하고 복원하는 데 사용됩니다. 어떤 경우에는 gho 파일을 삭제할 수 있지만 주의해서 삭제하십시오. 이번 글에서는 gho 파일의 역할, gho 파일 삭제 시 주의사항, gho 파일 삭제 방법에 대해 소개하겠습니다. 먼저 gho 파일의 역할을 이해해 봅시다. gho 파일은 전체 하드 디스크 또는 특정 파티션의 이미지를 저장할 수 있는 압축된 시스템 및 데이터 백업 파일입니다. 이러한 종류의 백업 파일은 일반적으로 응급 복구에 사용됩니다.

해결 방법: Java 파일 작업 오류: 파일 쓰기 실패 해결 방법: Java 파일 작업 오류: 파일 쓰기 실패 Aug 26, 2023 pm 09:13 PM

해결 방법: Java 파일 작업 오류: 파일 쓰기에 실패했습니다. Java 프로그래밍에서는 파일 작업이 필요한 경우가 많으며 파일 쓰기는 중요한 기능 중 하나입니다. 그러나 때때로 파일 쓰기 실패 오류가 발생하여 프로그램이 제대로 실행되지 않을 수 있습니다. 이 문서에서는 이러한 유형의 문제를 해결하는 데 도움이 되는 몇 가지 일반적인 원인과 해결 방법을 설명합니다. 잘못된 경로: 일반적인 문제는 잘못된 파일 경로입니다. 지정된 경로에 파일을 쓰려고 할 때 해당 경로가 존재하지 않거나 권한이 부족하면 파일이 쓰이게 됩니다.

Go 프로그래밍 팁: 파일에서 내용 삭제하기 Go 프로그래밍 팁: 파일에서 내용 삭제하기 Apr 04, 2024 am 10:06 AM

Go 언어는 파일 내용을 지우는 두 가지 방법, 즉 io.Seek 및 io.Truncate를 사용하거나 ioutil.WriteFile을 사용하는 방법을 제공합니다. 방법 1은 커서를 파일 끝으로 이동한 다음 파일을 자르는 것이고, 방법 2는 빈 바이트 배열을 파일에 쓰는 것입니다. 실제 사례에서는 이 두 가지 방법을 사용하여 Markdown 파일의 콘텐츠를 지우는 방법을 보여줍니다.

C# 개발에서 XML 및 JSON 데이터 형식을 처리하는 방법 C# 개발에서 XML 및 JSON 데이터 형식을 처리하는 방법 Oct 09, 2023 pm 06:15 PM

C# 개발에서 XML 및 JSON 데이터 형식을 처리하려면 특정 코드 예제가 필요합니다. 최신 소프트웨어 개발에서는 XML과 JSON이 널리 사용되는 두 가지 데이터 형식입니다. XML(Extensible Markup Language)은 데이터를 저장하고 전송하는 데 사용되는 마크업 언어인 반면, JSON(JavaScript Object Notation)은 경량 데이터 교환 형식입니다. C# 개발에서는 XML 및 JSON 데이터를 처리하고 조작해야 하는 경우가 많습니다. 이 기사에서는 C#을 사용하여 이 두 가지 데이터 형식을 처리하고 첨부하는 방법에 중점을 둘 것입니다.

C++를 사용하여 파일의 지정된 위치에 콘텐츠를 삽입하는 방법은 무엇입니까? C++를 사용하여 파일의 지정된 위치에 콘텐츠를 삽입하는 방법은 무엇입니까? Jun 04, 2024 pm 03:34 PM

C++에서는 ofstream 클래스를 사용하여 파일의 지정된 위치에 콘텐츠를 삽입합니다. 파일을 열고 삽입 지점을 찾습니다. 사용

See all articles