Jibx简单示例

@import url(http://www.blogjava.net/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
首先从 JiBX 网站下载 JiBX,当前最新版本是 beta 3。解开下载的 zip 文件,里面有一个 lib 目录,包含了 bcel.jar, jibx-bind.jar, jibx-extras.jar, jibx-run.jar, xpp3.jar 五个 jar 文件。bcel.jar, jibx-bind.jar 只有在 binding compiler 的时候才用得到。jibx-extras.jar 是一个可选的工具包,里面有一些测试和验证的工具类。 
1.定义一个我们将要处理 XML 文件,文件名为 data.xml,内容如下: 

<customer> 
<person> 
  
<cust-num>123456789</cust-num> 
  
<first-name>John</first-name> 
  
<last-name>Smith</last-name> 
</person> 
<street>12345 Happy Lane</street> 
<city>Plunk</city> 
<state>WA</state> 
<zip>98059</zip> 
<phone>888.555.1234</phone> 
</customer> 
这个 XML 文件非常简单,共有十个元素,没有属性。根元素 customer 有 person, street, city, state, zip, phone 六个子元素。其中元素 person 有 cust-num, first-name, last-name 三个子元素。 
2.接着定义两个 Java 类 Customer 和 Person,也采用最简单的方式,用对象的域值对应元素,内容如下: 

public class Customer { 
  
public Person person; 
  
public String street; 
  
public String city; 
  
public String state; 
  
public Integer zip; 
  
public String phone; 


public class Person { 
  
public int customerNumber; 
  
public String firstName; 
  
public String lastName; 
这个两个类没有任何方法,够简单吧!或许你已经看出来了,Customer 类的七个 field 对应的是 XML 文件中 customer 元素的七个子元素。Person 类的三个 field 对应的是 person 元素的三个子元素。在 Person 类的 field 的名称并不是和 person 元素的子元素名称完全相等,这是遵守 Java 编程规范 field 命名的需要,虽然不相等,但这不重要,可以在绑定定义文挡中把它们一一对应起来。 
3.绑定定义文挡 
绑定定义文挡是依据绑定定义规范将 XML 数据和 Java 对象绑定的 XML 文挡。文件名为 binding.xml,内容如下: 


binding.xml 文件中的 name 和 field 属性分别将 XML 中的元素和 Java 对象中的 field 一一对应并绑定起来。 

<mapping name="customer" class="Customer"> 
mapping 元素的 name 和 class 属性将 customer 根元素和 Customer 类绑定在一起。 

<structure name="person" field="person"> 

public Person person; 
上面两行定义了 person 是 Customer 的 field,同时也把 person 元素和 person 类绑定在一起。 

<binding> 
<mapping name="customer" class="Customer"> 
  
<structure name="person" field="person"> 
   
<value name="cust-num" field="customerNumber"/> 
   
<value name="first-name" field="firstName"/> 
   
<value name="last-name" field="lastName"/> 
  
</structure> 
  
<value name="street" field="street"/> 
  
<value name="city" field="city"/> 
  
<value name="state" field="state"/> 
  
<value name="zip" field="zip"/> 
  
<value name="phone" field="phone"/> 
</mapping> 
</binding> 
4.执行 Binding Compiler 过程 
以下命令是在 Linux 下执行,如果是 Windows 平台请转换成相应的命令 

#javac Person.java 
#javac 
-classpath . Customer.java 
#java 
-jar lib/jibx-bind.jar binding.xml 
执行完后,在当前目录多了四个 class 文件,分别是 Person.class, Customer.class, JiBX_bindingCustomer_access.class, JiBX_bindingFactory.class。 
5.执行 binding runtime 过程 
接着写一个简单的读取 data.xml 测试程序 Test.java,内容如下: 

import java.io.FileInputStream; 
import java.io.FileNotFoundException; 

import org.jibx.runtime.JiBXException; 
import org.jibx.runtime.IBindingFactory; 
import org.jibx.runtime.BindingDirectory; 
import org.jibx.runtime.IUnmarshallingContext; 

class Test { 
  
public static void main(String[] args) { 
  
try
    IBindingFactory bfact 
= BindingDirectory.getFactory(Customer.class); 
    IUnmarshallingContext uctx 
= bfact.createUnmarshallingContext(); 
    Customer customer 
= (Customer)uctx.unmarshalDocument(new FileInputStream("data.xml"), null); 
    Person person 
= customer.person; 

    System.out.println(
"cust-num:" + person.customerNumber); 
    System.out.println(
"first-name:" + person.firstName); 
    System.out.println(
"last-name:" + person.lastName); 
    System.out.println(
"street:" + customer.street); 
  }
catch(FileNotFoundException e){ 
    System.out.println(e.toString()); 
  }
catch(JiBXException e){ 
    System.out.println(e.toString()); 
  } 

编译并运行这个测试程序 

#javac -classpath .:lib/jibx-run.jar Test.java 
#java 
-cp .:lib/jibx-run.jar:lib/xpp3.jar Test 
程序运行的结果是 

cust-num:123456789 
first
-name:John 
last
-name:Smith 
street:
12345 Happy Lane  

posted @ 2011-11-28 17:16 王树东 阅读(2517) | 评论 (0)编辑 收藏

Groovy Eclipse 插件安装失败

@import url(http://www.blogjava.net/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css); 最近不知道Groovy在搞什么鬼, Eclipse在线插件的安装总是有问题。
然后只能在网上找到插件的压缩包,下载后再安装就好了。步骤如下:
1.    下载groovy 插件的安装包,链接:
        For Eclipse 3.7:
        http://dist.springsource.org/release/GRECLIPSE/e3.7/archive-2.5.1.xx-20110628-1600-e37.zip 
        For Eclipse 3.6: 
        http://dist.springsource.org/release/GRECLIPSE/e3.6/archive-2.5.1.xx-20110627-1300-e36.zip

2.    进入eclipse安装插件的页面,点击Add 添加新的插件,在弹出的对话框中选择Archieve
        然后选择下载的压缩文件,安装就可以了。

posted @ 2011-11-20 21:33 王树东 阅读(1720) | 评论 (0)编辑 收藏

压缩文件以及文件夹

@import url(http://www.blogjava.net/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
//使用Groovy 稍微改了下
import
 java.io.File;
import java.io.FileInputStream;
import java.util.zip.GZIPOutputStream 
import java.util.zip.ZipEntry 
import java.util.zip.ZipOutputStream 


class Compress {
    
    
public static gzipFile(from,to) throws IOException{
        def inFile 
= new FileInputStream(from);
        def out 
= new GZIPOutputStream(new FileOutputStream(to));
        
byte[] buffer = new byte[4096];
        def buffer_read 
= 0;
        
while((buffer_read = inFile.read(buffer)) != -1){
//            out.write(buffer,0,buffer_read);//use '<<' replace
            out << buffer;//use '<<' replace
        }
        inFile.close();
        out.close();
    }
    
    
public static zipDirectory(dir,zipFile){
        File dire 
= new File(dir);
        
if(!dire.isDirectory()){
            
throw new IllegalArgumentException('Compress: not a directory:' + dir);
        }
        String[] entries 
= dire.list();
        
byte[] buffer = new byte[4096];
        
int bytes_read;
        
        ZipOutputStream out 
= new ZipOutputStream(new FileOutputStream(zipFile));
        
        entries.each{item 
->
            File f 
= new File(dire,item);
            
if(f.isDirectory()){
                
return ;
            }
            FileInputStream in_file 
= new FileInputStream(f);
            ZipEntry entry 
= new ZipEntry(f.getPath());
            out.putNextEntry (entry);
            
while((bytes_read = in_file.read(buffer)) != -1){
                out 
<< buffer;
            }
            in_file.close();
        }
        out.close();
    }
    
    
static main(args) {
        def from 
= args[0];
        File from_file 
= new File(from);
        def directory 
= from_file.isDirectory();
        def to 
= '';
        
if(directory){
            to 
= from + '.zip';
        }
else{
            to 
= from + '.gz';
        }
        
        
if((new File(to)).exists()){
            println(
'Compress: won\'t overwrite existing file:' + to);
            System.exit(0);
        }
        
if(directory)
            Compress.zipDirectory (from, to);
        
else
            Compress.gzipFile from, to;
    }
}

posted @ 2011-07-22 12:55 王树东 阅读(271) | 评论 (0)编辑 收藏

对Java File类的操作-- delete

@import url(http://www.blogjava.net/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
执行File.delete()时最好做一系列的验证。
import java.io.File;
public class Delete {
    
public Delete() {
        
// TODO Auto-generated constructor stub
    }
    
/**
     * 
@param args
     
*/
    
public static void main(String[] args) {
        
if(args.length != 1){
            System.err.println(
"Usage:java Delete<file or directory>");
            System.exit(
0);
        }
        
        
try{
            delet1e(args[
0]);
        }
catch(IllegalArgumentException e){
            System.err.println(e.getMessage());
        }
    }
    
private static void delet1e(String fileName) {
        File f 
= new File(fileName);
        
if(!f.exists())
            fail(
"Delete:no such file or firectory:" + fileName);
        
if(!f.canWrite())
            fail(
"Delete:write protected :" + fileName);
        
if(f.isDirectory()){
            String[] files 
= f.list();
            
if(files.length > 0)
                fail(
"Delete:directory not empty:" + fileName);
        }
        
boolean success = f.delete();
        
if(!success)
            fail(
"Delete: delete failed");
    }
    
private static void fail(String msg)throws IllegalArgumentException {
        
// TODO Auto-generated method stub
        throw new IllegalArgumentException(msg);
    }
}

posted @ 2011-07-07 13:13 王树东 阅读(1169) | 评论 (0)编辑 收藏

Java Object 序列化成XML以及XML反序列化成Java Object

@import url(http://www.blogjava.net/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
package org.sl.bean;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;

public class ObjectXmlSerial {
   
    public static void main(String[] args) throws IOException{
        UserBean user = new UserBean();
        OtherUserInfoBean otherUserInfo = new OtherUserInfoBean();
       
        otherUserInfo.setAddress("汉字");
        otherUserInfo.setEmail("test@test.com");
       
        user.setName("hello");
        user.setPassword("world");
       
        user.setOtherUserInfo(otherUserInfo);
                         
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        BufferedOutputStream bufferOut = new BufferedOutputStream(byteArrayOut);
       
        writeObjectToXML(bufferOut, user);
        byte[] bys = byteArrayOut.toByteArray();
       
        byteArrayOut.close();
        bufferOut.close();
       
       
        ByteArrayInputStream byteArrayIn = new ByteArrayInputStream(bys);
        BufferedInputStream bufferIn = new BufferedInputStream(byteArrayIn);
       
        UserBean user1 = readObjectFromXML(bufferIn);
       
        byteArrayIn.close();
        bufferIn.close();       
       
        System.out.println(user1.getName());
        System.out.println(user1.getOtherUserInfo().getAddress());
    }
   
    public static <T extends Serializable> void writeObjectToXML(OutputStream out, T obj){
        XMLEncoder xmlEncoder = null;
       
        try{
            xmlEncoder = new XMLEncoder(out);
            xmlEncoder.writeObject(obj);
        }finally{
            if(null != xmlEncoder)
                xmlEncoder.close();
        }
    }
   
    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T readObjectFromXML(InputStream in){
        T obj = null;
        XMLDecoder xmlDecoder = null;
       
        try{
            xmlDecoder = new XMLDecoder(in);
            obj = (T) xmlDecoder.readObject();
        }finally{
            if(null != xmlDecoder)
                xmlDecoder.close();
        }
        return obj;
    }
}

posted @ 2011-07-04 20:55 王树东 阅读(1689) | 评论 (0)编辑 收藏

仅列出标题
共2页: 上一页 1 2 
<2024年5月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

导航

统计

公告

常用链接

留言簿

随笔分类(17)

随笔档案(15)

文章分类(4)

文章档案(5)

收藏夹(4)

Algorithm

Design

Environment Setup

Installer

Maven

MINA

OS

Skills for Java

VIM

搜索

最新评论

阅读排行榜

评论排行榜