插件开发:如何将document对象读取到文件中

如何将document对象读取到文件中

1、获取document流

//Messages.FILE_STYLE:工程中的文件夹名称;Messages.DEFAULT_ABF4A:工程中文件夹下的文件名称;
Document abfDoc = Dom4jUtil
					.getDocument(TemplateObtain.getTemplateInputStream(Messages.FILE_STYLE, Messages.DEFAULT_ABF4A));
/**
	 * @param style
	 *            模板类型
	 * @param templateName
	 *            模板名称
	 * @return
	 */
	public static InputStream getTemplateInputStream(String style, String templateName) {

		if ("".equals(style)) {
			return null;
		}

		try {
			URL url = Activator.getDefault().getBundle().getEntry(style + "/" + templateName);
			return url.openStream();
		} catch (MalformedURLException e) {
			logger.error(e.getMessage());
		} catch (IOException e1) {
			logger.error(e1.getMessage());
		}
		return null;

	}

此为工程中的路径位置:
在这里插入图片描述
2、获取文件流

public static IFolder appFolder = ResourcesPlugin.getWorkspace().getRoot().getProject(appProject).getFolder(tradeName);
//获取abf4a文件(此文件为测试自定义文件)
IFile abfFile = Dom4jUtil.appFolder.getProject().getFolder(transName).getFile("test" + ".abf4a");

3、开始document转换文件

writeDomtoIfile(abfDoc, abfFile);
/**
	 * 将document写入ifile
	 */
	public static void writeDomtoIfile(Document document, IFile ifile) {
		//设置文件的输入格式
		OutputFormat format = OutputFormat.createPrettyPrint();
		//设置document中xml的文本字体
		format.setEncoding(document.getXMLEncoding());
		//新建字符串输入流
		StringWriter stringWriter = new StringWriter();
		//获取xml输入流
		XMLWriter writer = new XMLWriter(stringWriter, format);
		ByteArrayInputStream byteArrayInputStream = null;
		try {
			writer.write(document);
			byteArrayInputStream = new ByteArrayInputStream(stringWriter.toString().getBytes(ENCODE));
			if (ifile.exists()) {
				ifile.setContents(byteArrayInputStream, IResource.FORCE, new NullProgressMonitor());
			} else {
				ifile.create(byteArrayInputStream, IResource.FORCE, new NullProgressMonitor());
			}
			logger.info(ifile.getFullPath() + "写入成功");
		} catch (IOException | CoreException e) {
			logger.error("读取document到文件,写入失败!", e.fillInStackTrace());
		} finally {
			try {
				if (byteArrayInputStream != null)
					byteArrayInputStream.close();
				writer.close();
				stringWriter.close();
			} catch (Exception e) {
				logger.error("读取document到文件,关闭流失败!", e.fillInStackTrace());
			}
		}
	}

***此种获取方目前只测试用于插件开发;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值