使用了InputStreamReader進(jìn)行編碼轉(zhuǎn)換,但是輸出的漢字還是亂碼
package com.imooc.jdomtest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
public class JDOMTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//進(jìn)行對books.xml文件的JDOM解析
//準(zhǔn)備工作
//1.創(chuàng)建一個(gè)SAXBuilder對象
SAXBuilder saxBuilder = new SAXBuilder();
InputStream in;
try {
//2.創(chuàng)建一個(gè)輸入流,將XML文件加載到輸入流中來
in = new FileInputStream("src/res/books.xml");
InputStreamReader isr =new InputStreamReader(in, "UTF-8");
//3.通過saxBuilder的build方法,將輸入流加載到saxBuilder中
Document document= saxBuilder.build(isr);
//4.通過document對象獲取xml文件的根節(jié)點(diǎn)
Element rootelement = document.getRootElement();
//5.獲取根節(jié)點(diǎn)下的子節(jié)點(diǎn)的List集合
List<Element> bookList = rootelement.getChildren();
//繼續(xù)進(jìn)行解析
for (Element book : bookList) {
System.out.println("=======開始解析第"
+ (bookList.indexOf(book) + 1) + "書=======");
//解析book的屬性
List<Attribute> attrList = book.getAttributes();
//知道節(jié)點(diǎn)下屬性名稱時(shí),獲取屬性值
// book.getAttributeValue("id");
//遍歷attrList(針對不清楚book節(jié)點(diǎn)下屬性的名字及數(shù)量)
for (Attribute attr : attrList) {
//獲取屬性名
String attrName = attr.getName();
//獲取屬性值
String attrValue = attr.getValue();
System.out.println("屬性名:" + attrName +"---屬性值:" +attrValue);
}
//對book節(jié)點(diǎn)的子節(jié)點(diǎn)的節(jié)點(diǎn)名以及節(jié)點(diǎn)值的遍歷
List<Element> bookChilds = book.getChildren();
for (Element child : bookChilds) {
System.out.println("節(jié)點(diǎn)名:" + child.getName() + "------節(jié)點(diǎn)值:"
+ child.getValue());
}
System.out.println("=======結(jié)束解析第"
+ (bookList.indexOf(book) + 1) + "書=======");
}
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2017-12-10
InputStreamReader isr =new InputStreamReader(in, "UTF-8");--->InputStreamReader isr =new InputStreamReader(in, "gbk");? 就可以了
因?yàn)轫?xiàng)目的Resource---->Text file encodeing---->Inherited from container (GBK)