Java字符串集转换的例子

 

package net.maxwoods.xml;

import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.util.Set;
import java.util.SortedMap;
import javax.xml.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
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.Text;

public class xmlstr
{

	public static void main(String[] args)
	{
		try
		{
		System.out.println("当前JRE:" + System.getProperty("java.version")); 
		System.out.println("当前JVM的默认字符集:" + Charset.defaultCharset()); 
		SortedMap<String,Charset> a=Charset.availableCharsets();
		Set<String>  keys=a.keySet();
		System.out.println("字符集数:"+keys.size());
		for (String string : keys)
		{
			System.out.println(string);
		}
		Charset s=Charset.forName("GBK");
		System.out.println(s.displayName());
		System.out.println(s.name());
		// 生成XML
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
		DocumentBuilder builder=factory.newDocumentBuilder();
		Document doc = builder.newDocument();
		Element element=doc.createElement("测试");
		doc.appendChild(element);
		Text tn=doc.createTextNode("中文字符");
		element.appendChild(tn);
		System.out.println(DocumentToString(doc));
		System.out.println(doc.getXmlEncoding());
		}
		catch(Exception e)
		{
			
		}
	}
	
	public static String DocumentToString(Document doc)
	{
		try
		{
			TransformerFactory  tf  =  TransformerFactory.newInstance();
			Transformer t = tf.newTransformer();
			t.setOutputProperty(OutputKeys.ENCODING,"GBK");
			t.setOutputProperty(OutputKeys.INDENT, "yes");
			t.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml");
			t.setOutputProperty(OutputKeys.STANDALONE,"yes");
			ByteArrayOutputStream  bos  =  new  ByteArrayOutputStream();
			t.transform(new DOMSource(doc), new StreamResult(bos));
			byte[] bytes=bos.toByteArray();
			String x=new String(bytes,"GBK");
			System.out.println(x);
			return bos.toString("GBK");
		}
		catch(Exception e)
		{
			return "";
		}
	}
}

 

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享