posts - 51, comments - 17, trackbacks - 0, articles - 9
            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

          java 3322

          Posted on 2007-04-11 21:41 chenweicai 閱讀(166) 評論(0)  編輯  收藏

          1.
          import java.net.InetAddress;
          import java.net.UnknownHostException;

          public class NetWork {

           //static fields and static block
           
              //InetAddress of the local host
           private static InetAddress local = null;
           
           //integer version of the local host
           private static int packedLocal = 0;
           
           static {
            try{
             local = InetAddress.getLocalHost();
            }catch(UnknownHostException e){
             e.printStackTrace();
            }

            System.out.println("localhost : " + local);
            packedLocal = translate(local);
           }
           
           public static InetAddress getLocalHost(){
            return local;
           }
           
           public static String getLocalHostName(){
            return local.getHostName();
           }
           
           public static String getLocalMachineName(){
            String hostname = local.getHostName();
            int machEndIndex = hostname.indexOf('.');
            if(machEndIndex == -1)
             return hostname;
            else
             return hostname.substring(0, machEndIndex);
           }
           
           public static boolean isLocal(InetAddress address){
            return local.equals(address);
           }
           
           public static boolean isLocal(int packedAddress){
            return packedAddress == packedLocal;
           }
           
           /**
            * return an integer representation of the specified
            * InetAddress. This is used for efficiency
            */
           public static int translate(InetAddress address){
            byte[] ad = address.getAddress();//原始IP地址
            if(ad.length != 4)
             throw new IllegalArgumentException("only accept 32-byte IP address");
            int packedAddress = ((ad[0] << 24) & 0xFF000000) |
                 ((ad[1] << 16) & 0xFF0000) |
                 ((ad[2] <<  8) & 0xFF00) |
                 (ad[3] & 0xFF);
            return packedAddress;
           }
           
           /**
            * return an InetAddress representation of the specified integer.
            * This is used for performance improvements in serivalization.
            */
           public static InetAddress translate (int packed)
            throws UnknownHostException{
            int[] ad = new int[4];
               ad[0] = (packed  >>> 24);
               ad[1] = ((packed >>> 16) & 0x000000FF);
               ad[2] = ((packed >>>  8) & 0x000000FF);
               ad[3] = (packed          & 0x000000FF);
               StringBuffer buf = new StringBuffer();
               buf.append(ad[0]);
               buf.append(".");
               buf.append(ad[1]);
               buf.append(".");
               buf.append(ad[2]);
               buf.append(".");
               buf.append(ad[3]);
              
               return InetAddress.getByName(buf.toString());
           }
           
           public static String translateToString(int packed){
            int[] ad = new int[4];
            ad[0] = (packed >>> 24);
            ad[1] = ((packed >>> 16) & 0x000000FF);
            ad[2] = ((packed >>> 8) & 0x000000FF);
            ad[3] = (packed & 0x000000FF);
            
            StringBuffer buf = new StringBuffer();
            buf.append(ad[0]);
            buf.append(".");
            buf.append(ad[1]);
            buf.append(".");
            buf.append(ad[2]);
            buf.append(".");
            buf.append(ad[3]);
            
            return buf.toString();
           }
           
           public static void main(String[] args){
            InetAddress localhost = getLocalHost();
            System.out.println("Local Host Name is : " + getLocalHostName());
            System.out.println("Local Host Machine Name is : " + getLocalMachineName());
            if(isLocal(localhost))
             System.out.println(localhost.getHostName() + " is Local Host.");
            int intforaddress = translate(localhost);
            System.out.println("localhost integer representation is " + intforaddress);
            System.out.println("localhost string representation is " + translateToString(intforaddress));
            System.out.println(translateToString(intforaddress).toString());
            
           }
          }



          2. public interfece Externalizable extendx Serializable
          Externalizable 實例類的惟一特性是可以被寫入序列化流中,該類負責保存和恢復實例內容。 若某個要完全控制某一對象及其超類型的流格式和內容,則它要實現(xiàn) Externalizable 接口的 writeExternal 和 readExternal 方法。這些方法必須顯式與超類型進行協(xié)調以保存其狀態(tài)。這些方法將代替自定義的 writeObject 和 readObject 方法實現(xiàn)。
          Serialization 對象將使用 Serializable 和 Externalizable 接口。對象持久性機制也可以使用它們。要存儲的每個對象都需要檢測是否支持 Externalizable 接口。如果對象支持 Externalizable,則調用 writeExternal 方法。如果對象不支持 Externalizable 但實現(xiàn)了 Serializable,則使用 ObjectOutputStream 保存該對象。
          在重構 Externalizable 對象時,先使用無參數(shù)的公共構造方法創(chuàng)建一個實例,然后調用 readExternal 方法。通過從 ObjectInputStream 中讀取 Serializable 對象可以恢復這些對象。
          Externalizable 實例可以通過 Serializable 接口中記錄的 writeReplace 和 readResolve 方法來指派一個替代對象。

          writeExternal

          void writeExternal(ObjectOutput out)
          throws IOException
          該對象可實現(xiàn) writeExternal 方法來保存其內容,它可以通過調用 DataOutput 的方法來保存其基本值,或調用 ObjectOutput 的 writeObject 方法來保存對象、字符串和數(shù)組。

           

          參數(shù):
          out - 要寫入對象的流
          拋出:
          IOException - 包含可能發(fā)生的所有 I/O 異常

          readExternal

          void readExternal(ObjectInput in)
          throws IOException,
          ClassNotFoundException
          對象實現(xiàn) readExternal 方法來恢復其內容,它通過調用 DataInput 的方法來恢復其基礎類型,調用 readObject 來恢復對象、字符串和數(shù)組。readExternal 方法必須按照與 writeExternal 方法寫入值時使用的相同順序和類型來讀取這些值。

           

          參數(shù):
          in - 為了恢復對象而從中讀取數(shù)據(jù)的流
          拋出:
          IOException - 如果發(fā)生 I/O 錯誤
          ClassNotFoundException - 如果無法找到需要恢復的某個對象的類。

          import java.io.Externalizable;
          import java.net.InetAddress;

          public interface EndPoint extends Externalizable {

           /**
            *
            * @return Returns the IP address contained in this endpoint.
            */
           public InetAddress getAddress();
           
           /**
            * returns the IP address contained in this endpoint.
            * enclosed in an integer value.
            */
           public int getIntAddress();
           
           /**
            * Returns the port number contained in this endpoint.
            */
           public int getPort();
           
           
           /**
            * Return true if this endpoint is the local endpoint.
            */
           public boolean isLocal();
           
           /**
            * Returns true if this endpoint is a multicast endpoint.
            */
           public boolean isMulticastEndPoint();
          }



          import internet.network.NetWork;

          import java.io.Externalizable;
          import java.io.FileInputStream;
          import java.io.FileNotFoundException;
          import java.io.FileOutputStream;
          import java.io.IOException;
          import java.io.ObjectInput;
          import java.io.ObjectInputStream;
          import java.io.ObjectOutput;
          import java.io.ObjectOutputStream;
          import java.net.InetAddress;
          import java.net.UnknownHostException;

          public class EndPointImpl implements EndPoint, Comparable, Externalizable{

           //Constants
           
           /* Size of this object (in bytes) when marshalled. */
           public static final int SIZE = 6;
           
           //Fields
           protected InetAddress address;
           
           private int packedAddress;
           
           private int port;
           
           protected boolean local;
           
           //Constructors
           
           /**
            * Default constructor for externalization
            */
           public EndPointImpl(){
            
           }
           
           public EndPointImpl(InetAddress address, int port){
            this.address = address;
            this.port = port;
            packedAddress = NetWork.translate(address);
            local = NetWork.isLocal(packedAddress);
           }
           
           public EndPointImpl(int packedAddress, int port){
            this.packedAddress = packedAddress;
            this.port = port;
            this.local = NetWork.isLocal(packedAddress);
            //The InetAddress version of the address is computed
            //only when needed, to avoid uselesss DNS lookups.
            address = null;
           }
           
           public InetAddress getAddress() {
            if(address == null)
             try{
              address = NetWork.translate(packedAddress);
             }catch(UnknownHostException e){
              System.out.println(e.getMessage());
             }
             return address;
           }

           public int getIntAddress() {
            return this.packedAddress;
           }

           public int getPort() {
            return this.port;
           }

           public boolean isLocal() {
            return this.local;
           }

           public boolean isMulticastEndPoint() {
            return address.isMulticastAddress();
           }
           
           
           ////////////////////////////////////////////////////////////
           // Methods from Externalizable
           ////////////////////////////////////////////////////////////

           /**
            * Restores the content of this object form the marshaled data contained
            * in the specified input stream.
            *
            * @param in the stream to be read.
            */
           public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
            
            packedAddress = in.readInt();
            port = (int) in.readUnsignedShort();
            local = NetWork.isLocal(packedAddress);
            address = null;
           }

           /**
            * Marshals the content of this object to the specified output stream.
            *
            * @param out the stream to be written
            */
           public void writeExternal(ObjectOutput out) throws IOException {
            
            out.writeInt(packedAddress);
            out.writeShort(port);
           }

           
           ////////////////////////////////////////////////////////////
           // Methods from Object and Comparable
           ////////////////////////////////////////////////////////////
           /**
            *  Compares this object with the specified object for order.
            */
           public int compareTo(Object obj) {
            if(this == obj){
             return 0;
            }
            else{
             EndPointImpl endpoint = (EndPointImpl) obj;
             if(packedAddress < endpoint.packedAddress){
              return -1;
             }
             else if(packedAddress == endpoint.packedAddress){
              if(port < endpoint.port)
               return -1;
              else if(port == endpoint.port)
               return 0;
              else
               return 1;
             }
             else{
              return 1;
             }
            }
           }
           
           public int hashcode(){
            return packedAddress ^ port;
           }

           /**
            * Compares two EndPointImpl objects for content equality.
            */
           public boolean equals (Object obj){
            if(!(obj instanceof EndPointImpl))
             return false;
            EndPointImpl endpoint = (EndPointImpl) obj;
            return (endpoint.packedAddress == packedAddress && endpoint.port == port);
           }
           
           /**
            * Returns a string representation of this object.
            */
           public String toString(){
            StringBuffer buf = new StringBuffer();
            buf.append("[");
            buf.append(NetWork.translateToString(packedAddress));
            buf.append(":");
            buf.append(port);
            buf.append("]");
            
            return buf.toString();
           }
           
           
           public static void main(String[] args) throws FileNotFoundException, IOException{
            InetAddress localhost = NetWork.getLocalHost();
            EndPointImpl endpoint = new EndPointImpl(localhost, 100);
            System.out.println("This EndPoint is : " + endpoint.toString());
            EndPointImpl endpoint2 = new EndPointImpl();
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("endpoint.txt"));
            try {
             endpoint.writeExternal(oos);
            } catch (IOException e) {
             e.printStackTrace();
            }
            oos.close();
            
            ObjectInputStream ios = new ObjectInputStream(new FileInputStream("endpoint.txt"));
            try {
             endpoint2.readExternal(ios);
            } catch (IOException e) {
             e.printStackTrace();
            } catch (ClassNotFoundException e) {
             e.printStackTrace();
            }
            ios.close();
            System.out.println("This EndPoint is : " + endpoint2.toString());
           }
          }


          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導航:
           
          主站蜘蛛池模板: 甘南县| 邮箱| 曲麻莱县| 金湖县| 兰西县| 吉隆县| 黑龙江省| 庆云县| 马边| 临朐县| 登封市| 南乐县| 枞阳县| 阿尔山市| 高淳县| 哈尔滨市| 崇礼县| 麻栗坡县| 英德市| 武义县| 莎车县| 施秉县| 扬州市| 延川县| 句容市| 雅江县| 葫芦岛市| 昭通市| 明水县| 湖南省| 浙江省| 资中县| 东港市| 田阳县| 隆子县| 房产| 甘谷县| 太湖县| 金寨县| 凌源市| 涞水县|