通过正则表达取出xml属性中的字符串,并转换为图片

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import sun.misc.BASE64Decoder;

/**
 * 从xml中的属性中取出图片
 *
 * @author 艾客
 *
 * jdom、dom4j从xml中的节点的属性中获取base64转换的后的字符串有问题(备注:如果这个特殊的字符串在节点下【eg:<t>经过base64编码的图片字符串</t>】,获取节点的text值在转图片,则正常)
 */
public class ConvertImage {

 public static void main(String[] args) throws Exception, IOException {
  String string = inputStream2String(new FileInputStream("d:\\a.xml"));

  // Pattern p = Pattern.compile("PK_EventId=\"(.*?)\"");
  //Pattern p = Pattern.compile("PRINTENTITY=\"([^.]*)\"");//匹配非换行符
  Pattern p = Pattern.compile("PRINTENTITY=\"([\\s\\S]*)\"");//\s\S 匹配任何空白字符+匹配任何非空白字符
   //Pattern p = Pattern.compile("PRINTENTITY=[\"\']([\\s\\S]*)[\"\']");
  Matcher m = p.matcher(string);

  String img = "";
  System.out.println("===========================");
  while (m.find()) {
   img = m.group(1);
   System.out.println(img);
  }
  System.out.println("===========================");

  BASE64Decoder decoder = new BASE64Decoder();
  byte[] data = decoder.decodeBuffer(img);
  FileOutputStream os = new FileOutputStream("D:\\001.jpg");
  os.write(data);
  os.flush();
  os.close();

 }

 public static String inputStream2String(InputStream inStream) throws IOException {
  String lineSeparator = System.getProperty("line.separator");

  StringBuffer sb = new StringBuffer();
  BufferedReader bufferReader = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
  String str = null;
  while ((str = bufferReader.readLine()) != null) {
   sb.append(str + lineSeparator);
  }
  if (null == sb || sb.length() == 0) {
   return null;
  }

  return sb.toString();
 }
}
 

你可能感兴趣的:(xml,图片,附件)