java castor_Castor简单介绍

本节摘要:本节主要介绍Castor插件的使用。

preparation

1.castor简介

castor是一种将java对象和XML自动绑定的开源软件。它可以在java对象、XML文本、SQL数据表以及LDAP目录之间绑定。Castor几乎是JAXB的替代品。Castor是ExoLab Group下面的一个开放源代码的项目,它主要实现的是O/R映射功能。它主要API和数据接口为:JDO-like, SQL, OQL, JDBC, LDAP, XML, DSML。它支持分布式目录事务处理和时间;提供处理XML、Directory、XADirectory的类库,提供从XML到JAVA类的转换机制。Castor(http://castor.exolab..org/)是一种将Java对象和XML自动绑定的开源软件。它可以在Java对象、XML文本、SQL数据表以及LDAP目录之间绑定。

2.下载需要用到的jar包

castor-1.0.1-xml.jar包下载地址:

xercesImpl.jar包下载地址:

也可以从下面的链接下载,以上两个jar包我都已经上传

3.项目环境

system:win7  myeclipse:6.5  Tomcat:5.0  JDK:1.5    castor:1.0

项目结构图如下:

7382e172c3cb012504f95521b872a661.png

4.class&method

start

castor第一种用法:不使用xml配置文件

代码如下:

核心转换类--->DefaultCastor.java

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.pngDefaultCastor.java

1 packagecom.castor.def;2

3 importjava.io.File;4 importjava.io.FileNotFoundException;5 importjava.io.FileReader;6 importjava.io.FileWriter;7 importjava.io.IOException;8 importjava.io.Reader;9 importjava.io.Writer;10 importorg.exolab.castor.xml.MarshalException;11 importorg.exolab.castor.xml.Marshaller;12 importorg.exolab.castor.xml.Unmarshaller;13 importorg.exolab.castor.xml.ValidationException;14

15 /**

16 *17 *Module: DefaultCastor.java18 *Description: 缺省的用法,无xml配置文件,javabean和XM的互转19 *Company:20 *Author: ptp21 *Date: Apr 18, 201222 */

23 public classDefaultCastor {24

25 //getAbsolutePath();返回此抽象路径名的绝对路径名字符串

26 public static final String xmlPath = new File("").getAbsolutePath()27 + "/src/com/castor/def/";;28

29 /*

30 * 缺省用法:javabean转换为xml31 * 缺省用法没有配置文件,即javabean和xml的映射文件32 * 编组(marshalling)33 */

34 public static void defJavaBeanToXML() throwsIOException, MarshalException, ValidationException{35 UserInfo userInfo = newUserInfo();36 userInfo.setUsername("张三");37 userInfo.setPassword("123456");38 File file = new File(xmlPath + "test.xml");//通过将给定路径名字符串转换为抽象路径名来创建一个新 File 实例

39 Writer writer = new FileWriter(file);//根据给定的 File 对象构造一个 FileWriter对象

40 Marshaller marshaller = newMarshaller(writer);41 marshaller.setEncoding("gbk");//设置xml的编码,默认的是UTF-8,显示的中文为乱码

42 marshaller.marshal(userInfo);43 //Marshaller.marshal(userInfo, writer);

44 }45

46 /*

47 * 缺省用法:xml转换为javabean48 * 缺省用法没有配置文件,即javabean和xml的映射文件49 * 解组(unmarshalling)50 */

51 public static void defXMLToJavaBean() throwsFileNotFoundException, MarshalException, ValidationException{52 File file = new File(xmlPath + "test.xml");53 Reader reader = new FileReader(file);//在给定从中读取数据的 File 的情况下创建一个新 FileReader

54 UserInfo readUserInfo = (UserInfo) Unmarshaller.unmarshal(UserInfo.class,reader);55 System.out.println("****************************************\n");56 System.out.println("username=" + readUserInfo.getUsername()+"\t password="+readUserInfo.getPassword());57 System.out.println("\n****************************************");58

59 }60 public static void main(String[] args) throwsIOException,61 MarshalException, ValidationException {62 //javabean--->xml

63 defJavaBeanToXML();64 //xml--->javabean

65 defXMLToJavaBean();66

67 }68

69 }

使用的javabean--->UserInfo.java

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.pngUserInfo.java

1 packagecom.castor.def;2

3 public classUserInfo {4

5 publicString username;6 publicString password;7 publicString getUsername() {8 returnusername;9 }10 public voidsetUsername(String username) {11 this.username =username;12 }13 publicString getPassword() {14 returnpassword;15 }16 public voidsetPassword(String password) {17 this.password =password;18 }19 }

测试效果:

运行DefaultCastor.java类中的main方法,在控制台以及/src/com/castor/def/目录下查看生成的XML文件

控制台:

24dc9ea1d0ce3b36368ab652c2b605cf.png

生成的xml文件test.xml效果如图:

14928daf6150e914cd1f8da0b6687a5c.png

castor第二种用法:使用xml配置文件

代码如下:

javabean--->Book.java

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.pngBook.java

1 packagecom.castor.mapping;2

3 importjava.util.ArrayList;4 importjava.util.List;5

6 public classBook {7

8 privateString isbn;9 privateString title;10 private Listauthors;11

12 publicBook() {13 }14

15 public Book(String isbn, String title, Listauthors) {16 this.isbn =isbn;17 this.title =title;18 this.authors =authors;19 }20

21 publicBook(String isbn, String title, Author author) {22 this.isbn =isbn;23 this.title =title;24 this.authors = new ArrayList();25 this.authors.add(author);26 }27

28 public voidaddAuthor(Author author) {29 this.authors.add(author);30 }31

32 public ListgetAuthors() {33 returnauthors;34 }35

36 public void setAuthors(Listauthors) {37 this.authors =authors;38 }39

40 publicString getIsbn() {41 returnisbn;42 }43

44 public voidsetIsbn(String isbn) {45 this.isbn =isbn;46 }47

48 publicString getTitle() {49 returntitle;50 }51

52 public voidsetTitle(String title) {53 this.title =title;54 }55

56 }

javabean--->Author.java

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.pngAuthor.java

1 packagecom.castor.mapping;2

3 public classAuthor {4

5 privateString firstName;6 privateString lastName;7

8 publicAuthor() {9 }10

11 publicAuthor(String firstName, String lastName) {12 super();13 this.firstName =firstName;14 this.lastName =lastName;15 }16

17 public voidsetFirstName(String firstName) {18 this.firstName =firstName;19 }20

21 public voidsetLastName(String lastName) {22 this.lastName =lastName;23 }24

25 publicString getFirstName() {26 returnfirstName;27 }28

29 publicString getLastName() {30 returnlastName;31 }32 }

配置文件--->book-mapping.xml

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.pngbook-mapping.xml

1 <?xml version="1.0"?>

2 "http://castor.org/mapping.dtd">

4

5

6

14

15

16

17

18

19

20

21

22

23

24

25 collection="arraylist">

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

格式化相关类

读和写XML文件--->OperationFile.java

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.pngOperationFile.java

1 packagecom;2

3 importjava.io.BufferedReader;4 importjava.io.File;5 importjava.io.FileInputStream;6 importjava.io.FileNotFoundException;7 importjava.io.FileOutputStream;8 importjava.io.IOException;9 importjava.io.InputStream;10 importjava.io.InputStreamReader;11 importjava.io.OutputStream;12 importjava.io.UnsupportedEncodingException;13

14 /**

15 *Module: OperationFile.java16 *Description: 操作文件的工具类17 *Company:18 *Author: ptp19 *Date: Feb 13, 201220 */

21 public classOperationFile {22

23 /**

24 * 读取文件中的内容 存在中文乱码问题25 *@parampath26 *@return

27 *@throwsIOException28 */

29 public static String readFile1(String path) throwsIOException {30

31 //1.使用File类找到一个文件

32 File file = new File(path);//声明File对象33

34 //2.通过子类实例化父类对象

35 InputStream in = null;//准备好一个输入的对象

36 in = new FileInputStream(file);//通过对象的多态性,进行实例化37

38 //3.进行读操作

39 byte b[] = new byte[(int) file.length()];40 int len =in.read(b);41

42 //4.关闭输出流

43 in.close();44

45 //5.把byte数组转换为字符串

46 /*

47 * 通过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String48 * 参数:49 bytes - 要解码为字符的 byte 数组50 offset - 要解码的第一个 byte 的索引51 length - 要解码的 byte 数52 */

53 String str = new String(b, 0, len);54 returnstr;55 }56

57 /**

58 * 读文件,对于不知道文件大小采用的读取方式59 * 解决了读出的文件中文乱码问题60 *@paramfilePath61 *@return

62 */

63 public staticString readFile2(String filePath) {64 String fileContent = "";65 File file = newFile(filePath);66 if (file.isFile() &&file.exists()) {67 try{68 InputStreamReader read = newInputStreamReader(69 new FileInputStream(file), "GBK");70 BufferedReader reader = newBufferedReader(read);71 String line;72 try{73 while ((line = reader.readLine()) != null) {74 fileContent +=line;75 }76 reader.close();77 read.close();78 } catch(IOException e) {79 e.printStackTrace();80 }81

82 } catch(UnsupportedEncodingException e) {83 e.printStackTrace();84 } catch(FileNotFoundException e) {85 e.printStackTrace();86 }87 }88 returnfileContent;89 }90

91 /**

92 * 向文件中写入内容93 *@paramfilepath 写入文件的文件路径94 *@paramwrite 写入的内容95 *@paramflag1 是否覆盖,true-不覆盖原来的内容(追加),false-覆盖原来的内容96 *@paramflag2 是否换行,true-换行后写入,false-直接在文件末尾写入97 *@throwsIOException98 */

99 public static void writeFile(String filepath, String str, booleanflag1,100 boolean flag2) throwsIOException {101

102 //1.使用File类找到一个文件

103 File file = newFile(filepath);104

105 //2.通过子类实例化父类对象

106 OutputStream out = null;//准备好一个输出的对象107 //flag1=true,追加;flag1=false,覆盖

108 out = new FileOutputStream(file, flag1);//实例化109

110 //3.以循环的方式输出

111 String result = "";112 if(flag1) {113 if(flag2) {114 result = "\n" +str;115 } else{116 result =str;117 }118 } else{119 result =str;120 }121

122 byte b[] =result.getBytes();123 for (int i = 0; i < b.length; i++) {124 out.write(b[i]);125 }126 out.close();127 }128

129 public static void main(String args[]) throwsIOException{130 String filepath="d:\\a.txt";131 String str="写入的字符串";132 writeFile(filepath,str,false,true);133 }134

135 }

格式化XML类--->FormatXML.java

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.pngFormatXML.java

1 packagecom.format;2

3 importjava.io.IOException;4 importjava.io.StringReader;5 importjava.io.StringWriter;6 importjava.io.Writer;7

8 importorg.apache.xml.serialize.OutputFormat;9 importorg.apache.xml.serialize.XMLSerializer;10

11 importorg.w3c.dom.Document;12 importorg.xml.sax.InputSource;13 importorg.xml.sax.SAXException;14

15 importjavax.xml.parsers.DocumentBuilder;16 importjavax.xml.parsers.DocumentBuilderFactory;17 importjavax.xml.parsers.ParserConfigurationException;18

19 /**

20 *21 * Module: FormatXML.java22 * Description: 格式化xml23 * Company:24 * Author: ptp25 * Date: Apr 7, 201226 */

27 public classFormatXML {28

29 private staticDocument parseXMLFile(String in)30 throwsParserConfigurationException, SAXException, IOException {31 DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();32 DocumentBuilder db =dbf.newDocumentBuilder();33 InputSource is = new InputSource(newStringReader(in));34 returndb.parse(is);35 }36

37 public staticString formatXML(String unFormattedXml)38 throwsParserConfigurationException, SAXException, IOException {39 final Document document =parseXMLFile(unFormattedXml);40 OutputFormat format = newOutputFormat(document);41 format.setIndenting(true);42 format.setLineWidth(65);43 format.setIndent(2);44 format.setEncoding("GBK");45

46 Writer out = newStringWriter();47 XMLSerializer serializer = newXMLSerializer(out, format);48 serializer.serialize(document);49 returnout.toString();50 }51

52 public static void main(String[] args) throwsParserConfigurationException,53 SAXException, IOException {54 String unFormattedXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>123456张三李四";55 System.out.println("unFormattedXml:\n" +unFormattedXml);56 String formattedXml =formatXML(unFormattedXml);57 System.out.println("formattedXml:\n" +formattedXml);58 }59

60 }

测试类(java转xml)---BookMapMarshaller.java

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.pngBookMapMarshaller.java

1 packagecom.castor.mapping;2

3 importjava.io.File;4 importjava.io.FileWriter;5 importjava.io.IOException;6 importjava.util.ArrayList;7 importjava.util.Iterator;8 importjava.util.List;9

10 importjavax.xml.parsers.ParserConfigurationException;11

12 importorg.exolab.castor.mapping.Mapping;13 importorg.exolab.castor.mapping.MappingException;14 importorg.exolab.castor.xml.MarshalException;15 importorg.exolab.castor.xml.Marshaller;16 importorg.exolab.castor.xml.ValidationException;17 importorg.xml.sax.SAXException;18

19 importcom.OperationFile;20 importcom.castor.mapping.Author;21 importcom.castor.mapping.Book;22 importcom.format.FormatXML;23

24 public classBookMapMarshaller {25

26 //映射文件的路径

27 public static final String Mapping_XML = new File("").getAbsolutePath()28 + "/src/com/castor/mapping/";29 //解组后XML文件的路径

30 public static final String Result_XML = new File("").getAbsolutePath()31 + "/src/com/castor/mapping/";32

33 /**

34 * 编组(marshalling) java转换为xml35 *@throwsMappingException36 *@throwsIOException37 *@throwsValidationException38 *@throwsMarshalException39 *@throwsSAXException40 *@throwsParserConfigurationException41 */

42 @SuppressWarnings("unchecked")43 public static void main(String[] args) throwsIOException,44 MappingException, MarshalException, ValidationException,45 ParserConfigurationException, SAXException {46 //对对象设置值

47 List authors = new ArrayList();48 Book book = newBook();49 authors.add(new Author("三", "张"));50 authors.add(new Author("四", "李"));51 book.setAuthors(authors);52 book.setIsbn("6921505081308");53 book.setTitle("thinking in java");54

55 Mapping mapping = newMapping();56 //装载映射文件

57 mapping.loadMapping(Mapping_XML + "book-mapping.xml");58

59 //把解组后的文件输出到book-result.xml中

60 FileWriter writer = new FileWriter(Result_XML + "book-result.xml");61 Marshaller marshaller = newMarshaller(writer);62 marshaller.setMapping(mapping);63 marshaller.setEncoding("GBK");//解决中文乱码的问题

64 marshaller.marshal(book);65

66 /*

67 * 格式化book-result.xml文件68 */

69 //1.读取book-result.xml文件

70 String unFormattedXml =OperationFile.readFile2(Result_XML71 + "book-result.xml");72 //2.格式化XML文件

73 String formattedXml =FormatXML.formatXML(unFormattedXml);74 //3.写入到book-result.xml文件

75 OperationFile.writeFile(Result_XML + "book-result.xml", formattedXml,76 false, false);77

78 //打印对象的信息

79 System.out.println("Book ISBN: " +book.getIsbn());80 System.out.println("Book Title: " +book.getTitle());81 authors =book.getAuthors();82 for (Iterator i =authors.iterator(); i.hasNext();) {83 Author author =(Author) i.next();84 System.out.println("Author: " + author.getLastName() + " "

85 +author.getFirstName());86 }87 }88 }

测试效果:

运行BookMapMarshaller.java类中的main方法,在控制台以及/src/com/castor/def/目录下查看生成的XML文件

控制台:

39a5bf8cdd84baed7ceafd904f15cfa7.png

生成的xml文件 book-result.xml效果如下:

ab8f0ade3052e0c2fce44c57c832e8a3.png

result

note.txt文件是使用castor过程中遇到的一些文件以及相应的解决方法

java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory  at org.exolab.castor.util.Configuration.(Configuration.java:101)  at org.exolab.castor.xml.Marshaller.initialize(Marshaller.java:379)  at org.exolab.castor.xml.Marshaller.(Marshaller.java:337)  at com.castor.TestCastor.main(TestCastor.java:24) Exception in thread "main" 解决方案:导入commons-logging.jar包

java.lang.RuntimeException: Could not instantiate serializer org.apache.xml.serialize.XMLSerializer: java.lang.ClassNotFoundException: org.apache.xml.serialize.XMLSerializer  at org.exolab.castor.xml.XercesSerializer.(XercesSerializer.java:50)  at org.exolab.castor.xml.XercesXMLSerializerFactory.getSerializer(XercesXMLSerializerFactory.java:31)  at org.exolab.castor.util.LocalConfiguration.getSerializer(LocalConfiguration.java:531)  at org.exolab.castor.xml.Marshaller.(Marshaller.java:339)  at com.castor.TestCastor.main(TestCastor.java:24) Exception in thread "main" 解决方案:有些地方说是JDK1.5以下因为没有集成XMLSerializer类,故会报这个错误,但是我改为JDK1.5还是报这个错误 正确的解决方法是导入xercesImpl.jar包,jar包的下载路径如下为:http://archive.apache.org/dist/xml/xerces-j/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值