java Document文档处理工具类--写入转换(XML与File转Document)

11 篇文章 0 订阅
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;

import org.dom4j.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class DocumentUtil {
   public static Document createDocument()  {
	   try {
			// 初始化xml解析工厂
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			
			// 创建DocumentBuilder
			DocumentBuilder builder = factory.newDocumentBuilder();
			
			// 创建Document
			Document doc = (Document) builder.newDocument();

			doc.setXMLEncoding("UTF-8");
            return doc;
		} catch (Exception e) {
			e.printStackTrace();
		   throw new RuntimeException(e);
		}

   }
   public static Document parseXml(String in) {
       try {
           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
           DocumentBuilder db = dbf.newDocumentBuilder();
           InputSource is = new InputSource(new StringReader(in));
           return (Document) db.parse(is);
       } catch (ParserConfigurationException e) {
           throw new RuntimeException(e);
       } catch (SAXException e) {
           throw new RuntimeException(e);
       } catch (IOException e) {
           throw new RuntimeException(e);
       }
   }
   public static Document parseFile(File file){
	   try{
		   // 初始化xml解析工厂
		     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	
		   // 创建DocumentBuilder
		   DocumentBuilder builder = factory.newDocumentBuilder();
	
		   // 创建解析xml的Document
		   Document doc = (Document) builder.parse(file);
		   // 根节点名称
//		   String rootName = doc.getDocumentElement().getTagName();
//		   System.out.println("根节点: " + rootName);
//	
//		   System.out.println("递归解析--------------begin------------------");
//		   // 递归解析Element
//		   Element element = doc.getDocumentElement();
//		   parseElement(element);
//		   System.out.println("递归解析--------------end------------------");
		   return doc;

	   } catch (ParserConfigurationException e) {
	         e.printStackTrace();
	         throw new RuntimeException(e);
	   } catch (SAXException e) {
	          e.printStackTrace();
	          throw new RuntimeException(e);
	   } catch (IOException e) {
	        e.printStackTrace();
	        throw new RuntimeException(e);
	    }
	   }
   /**
    * 传入到哪个文件路径 传入生成的document
    * @param fileUrl 需要生成文件的路径
    * @param doc 生成的文档
    * @throws IOException
    */
   public static void write(String fileUrl, Document doc) throws IOException {
       File file = new File(fileUrl);
       write(file, "UTF-8", doc);
   }

   /**
    * 传入到哪个文件路径 传入生成的document
    * @param fileUrl 文件路径
    * @param charsetName 编码
    * @param doc 文档
    * @throws IOException
    */
   public static void write(String fileUrl,String charsetName, Document doc) throws IOException {
       File file = new File(fileUrl);
       write(file, charsetName, doc);
   }

   /**
    * 传入到哪个文件 传入生成的document
    * @param file
    * @param doc
    * @throws IOException
    */
   public static void write(File file, Document doc) throws IOException {
       write(file, "UTF-8", doc);
   }

   /**
    * 将document内容写入文件中
    * @param file
    * @param charsetName
    * @param doc
    * @throws IOException
    */
   public static void write(File file, String charsetName, Document doc) throws IOException {
	   try {
		   if (!file.exists()) {
	           file.createNewFile();
	       }
	       FileOutputStream fos = new FileOutputStream(file, false);
	       // 设置输出流
	       OutputStreamWriter osw = new OutputStreamWriter(fos, charsetName);
	       // 讲doc写入文件中
	       osw.write(doc.asXML());
	       osw.close();
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
      
   }

}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将XML格式的DOC或DOCX文档转换为DOCX格式,您可以使用Apache POI库来处理Word文档。以下是一个示例代码,展示了如何将XML格式的DOC或DOCX文档转换为DOCX格式: ```java import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.converter.WordToConverter; import org.apache.poi.hwpf.usermodel.Range; import java.io.FileInputStream; import java.io.FileOutputStream; public class XMLToDocxConverter { public static void main(String[] args) { try { // 读取XML格式的DOC或DOCX文件 FileInputStream fis = new FileInputStream("input.xml"); // 创建Word文档对象 XWPFDocument document = new XWPFDocument(); XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); // 将XML内容写入Word文档 byte[] buffer = new byte[fis.available()]; fis.read(buffer); run.setText(new String(buffer)); // 保存为DOCX格式的Word文档 FileOutputStream fos = new FileOutputStream("output.docx"); document.write(fos); // 关闭流 fos.close(); fis.close(); System.out.println("XML格式的DOC或DOCX文档已成功转换为DOCX格式!"); } catch (Exception e) { e.printStackTrace(); } } } ``` 上述示例代码使用Apache POI库中的XWPFDocument、XWPFParagraph和XWPFRun类来处理DOCX格式的Word文档,通过读取XML文件的内容并将其写入Word文档来实现转换。请确保您已将Apache POI库正确添加到项目中。 希望能对您有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值