zoukankan      html  css  js  c++  java
  • Re: help on converting bytearrayinputstream to objectinputstream [小糊涂的灵感]

    Re: help on converting bytearrayinputstream to objectinputstream
    Author: lightblue_daisy
    In Reply To: help on converting bytearrayinputstream to objectinputstream
    Jun 7, 2004 1:18 PM  
    Reply 5 of 5
    You have to writeObject first.

    A sample code as below, hope it's helpful.
    ----------------------------------------
                            
    try {
    //Using ByteArrayInputStream to simulate YOUR socket.getInputStream()
    String strSocketInput = "TAIWAN";
    ByteArrayInputStream baIn = new ByteArrayInputStream(strSocketInput.getBytes());
    DataInputStream oInputStream = new DataInputStream(baIn);

    byte[] arr = new byte[oInputStream.available()];
    oInputStream.read(arr);
    baIn.close();
    oInputStream.close();

    //A new byte array
    String strIdentifier = ", a beautiful country.";
    byte[] identifier = strIdentifier.getBytes();

    //the final one we will send
    byte[] ob = new byte[arr.length + identifier.length];
    ByteArrayInputStream baNew = new ByteArrayInputStream(arr);
    baNew.read(ob, 0, arr.length);
    //Append new byte array
    baNew = new ByteArrayInputStream(identifier);
    baNew.read(ob, arr.length, identifier.length);

    //== Coz we will invoke 'readObject', we have to 'writeObject' first.
    ByteArrayOutputStream baOut = new ByteArrayOutputStream();
    ObjectOutputStream objOut = new ObjectOutputStream(baOut);
    //write the object 'ob' to 'baOut'
    objOut.writeObject(ob);
    objOut.flush();
    objOut.close();

    //get the byte array of 'baOut'
    byte[] baSend = baOut.toByteArray();
    baOut.close();

    //retrieve the object 'ob'
    ByteArrayInputStream baRecIn = new ByteArrayInputStream(baSend);
    ObjectInputStream objIn = new ObjectInputStream(baRecIn);
    //the object type of 'ob' is byte[]
    byte[] baRec = (byte[])objIn.readObject();

    //see what we receive
    String strReceive = new String(baRec);
    System.out.println("WHAT WE RECEIVED: " + strReceive);
    } catch (Exception e) {
    e.printStackTrace();
    }
    Never giveup. Thanks the world.
  • 相关阅读:
    [C++] split string by string
    工作三个月心得经验
    Ubuntu Command-Line: Enable Unlimited Scrolling in the Terminal
    What is the PPA and How to do with it ?
    WCF vs ASMX WebService
    The ShortCuts in the ADT (to be continued)
    when does the View.ondraw method get called
    Browsing Storage Resources with Server Explorer
    Get start with Android development
    C++ Frequently asking question
  • 原文地址:https://www.cnblogs.com/cnsoft/p/58003.html
Copyright © 2011-2022 走看看