@import url(http://www.tkk7.com/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
@import url(http://www.tkk7.com/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
然后選擇下載的壓縮文件,安裝就可以了。
@import url(http://www.tkk7.com/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;
}
}
@import url(http://www.tkk7.com/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);
}
}
@import url(http://www.tkk7.com/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);