JAVA操作XML大全(2)原创
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* xml操作助手类
*
* @author FiliRon
* @see
*/
public final class XmlHelper {
private static final Log logger = LogFactory.getLog(XmlHelper.class);
/**
* 获取指定编码格式的reader
*
* @param xml
* @param encoding
* @return
*/
public static Reader getEncodingXmlReader(byte[] xml, String encoding) {
try {
return new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(xml), encoding));
} catch (UnsupportedEncodingException e) {
logger.debug("用指定编码[" + encoding + "]转化字节流时出现异常!" + e.getMessage());
return null;
}
}
/**
* 读取指定全路径名的文件内容,以字节流形式返回
*
* @param xmlFileFullName
* @return 异常返回null
*/
public static byte[] loadXmlFile(String xmlFileFullName) {
BufferedInputStream fInput = null;
try {
fInput = new BufferedInputStream(XmlHelper.class.getClassLoader()
.getResourceAsStream(xmlFileFullName));
byte[] result = new byte[fInput.available()];
fInput.read(result);
return result;
} catch (IOException e) {
logger.debug("读取指定文件发生异常!" + e.getMessage());
return null;
} finally {
try {
if (fInput != null) {
fInput.close();
}
} catch (IOException e) {
logger.debug("关闭BufferedInputStream时发生异常!" + e.getMessage());
}
}
}
/**
* 转化字节流的编码
*
* @param srcByte
* @param encoding
* @return 异常返回null
*/
public static byte[] changeEncoding(byte[] srcByte, String encoding) {
if (srcByte == null || srcByte.length <= 0) {
return null;
}
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(srcByte), encoding));
String line = new String();
StringBuffer strBuf = new StringBuffer();
while ((line = br.readLine()) != null) {
strBuf.append(line);
}
return strBuf.toString().getBytes();
} catch (Exception e) {
logger.debug("用指定编码转化字节流时发生异常!" + e.getMessage());
return null;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
logger.debug("关闭BufferedReader时发生异常!" + e.getMessage());
}
}
}
}
}
下面是单元测试:
import junit.framework.TestCase;
public class XmlHelperTest extends TestCase {
public void testLoadXmlFile() {
// 该文件使用UTF-8格式保存
String fileName = "cn/com/jdlssoft/daup/app/testfiles/xmlhelptest.txt";
byte[] fileContents = XmlHelper.loadXmlFile(fileName);
// 缺省字符集读出应该有问题
assertFalse("进行xmlhelp的测试".equals(new String(fileContents)));
fileContents = XmlHelper.changeEncoding(fileContents, "UTF-8");
// 用UTF-8转化后应该没有问题
assertEquals("进行xmlhelp的测试", new String(fileContents));
}
}
没有评论:
发表评论