Reading Objects using NIO

I having problems reading an object using NIO APIs. I am end creating an Object and pass it through a socket. When I retrieve the data from the input stream within the socket I initialize a ByteBuffer by allocating a length. The problem is that there is NO way of knowing what to allocate that ByteBuffer when reading in the object. Below is within a method that allows me to read information from the socket.
//Allocate the length ByteBuffer.
ByteBuffer buffer = ByteBuffer.allocate(1024);
//Read the data from the SocketChannel....PROBLEM IS WHAT IF I NEED TO DO MULTIPLE READS
socketChannel.read(buffer);
///We will create a byte array from the ByteBuffer.
byte[] b = buffer.array();
//ByteArrayInputStream that we will create and put the byte array in.
ByteArrayInputStream bis = new ByteArrayInputStream(b);
//ObjectInputStream where we will use the ByteArrayInputStream.
ObjectInputStream input = new ObjectInputStream(bis);
//Object that we will read in.
Object obj = input.readObject();
//Message that we will end up receiving.     
Message receivingMsg = null;
//Once we have our Message we will end up closing the connection.
bis.close();
input.close();
//We will clear the buffer.
buffer.clear();
//We will cast the object to a message object so
//that we can end up sending it through the right
//routine which will allow us to send a response
//back to the client. *********SPECIAL Class that will cast our generic object into a Message Object.
Message receivedFromClient = (Message) obj;
//we will end up taking that message and returning it.
Message returningMsg = communicate(receivedFromClient);
//Here we will end up taking the Message and putting it into the ByteBuffer.          
ByteBuffer bb = objectToOutputStreamByteBuffer(returningMsg);
socketChannel.write(bb);
----The problem is if I have more data within that Object. I need to re-allocate the ByteBuffer object and read everything on that socket. I tried the following code but I really don't feel it will be optimized the best for performance. I guess my question is that should I even be using NIO in this situation or Blocking IO?
Again, here is the code that will read multiple data from the socket until it is -1.
//Here we will read the information we received by first allocating
//a ByteBuffer object.
ByteBuffer buffer1 = ByteBuffer.allocate(5);
ByteBuffer buffer2 = ByteBuffer.allocate(0);
//We will read the data from this object.
while ((socketChannel.read(buffer1)) != -1) {
//We will check the Buffers and then try to recreate a new ByteBuffer that will put the remaining
//stuff within the buffer. NOT SURE IF THIS IS THE MOST EFFICIENT WAY OF DOING THIS
//AND ACTUALLY DON'T HAVE THE CODE WORKING CORRECTLY. THIS IS WHERE I
//NEED HELP ON THE CORRECT WAY TO DO THIS.
     if (buffer1.remaining() < buffer2.remaining()) {
          buffer1.flip();
          buffer2 = ByteBuffer.allocate(buffer1.remaining() + buffer2.remaining());
          System.out.println("tmp 2 Remaining : " + buffer2.remaining());
          //tmp.put(buffer2);
          //buffer2 = tmp;
          System.out.println("Buffer 2 Remaining : " + buffer2.remaining());
     buffer2.put(buffer1);
     buffer1.clear();
//We will create a byte array from the ByteBuffer.                    
byte[] b = buffer.array();
//ByteArrayInputStream that we will create and put the byte array in.
ByteArrayInputStream bis = new ByteArrayInputStream(b);
//ObjectInputStream where we will use the ByteArrayInputStream.
ObjectInputStream input = new ObjectInputStream(bis);
//Object that we will read in.
Object obj = input.readObject();
//Message that we will end up receiving.     
Message receivingMsg = null;
//Once we have our Message we will end up closing the connection.
bis.close();
input.close();
//We will clear the buffer.
buffer2.clear();
buffer1.clear();
//We will cast the object to a message object so
//that we can end up sending it through the right
//routine which will allow us to send a response
//back to the client.
Message receivedFromClient = (Message) obj;
//we will end up taking that message and returning it.
Message returningMsg = communicate(receivedFromClient);
//Here we will end up taking the Message and putting it into the ByteBuffer.          
ByteBuffer bb = objectToOutputStreamByteBuffer(returningMsg);
socketChannel.write(bb);
Any help would be greatly appreciated.

I use my own InputStream class overriding the two standard read functions read( byte[], index, length ) and read(). When you construct it pass in the channel you are reading from and read from the channel on demand. ie when a call to read comes in you read say 100 bytes from the channel. The call required only 80 so these are consumed and the other 20 are buffered. Another read call is made, this time for 50 bytes but we only have 20 buffered so another read of the channel is needed. It is up to you whether you break the contract of read( byte[], index, length ) to keep reading the channel until the full "length" is available, or handle this in your application code.
Then because this class is InputStream you can wrap it up inside any stream you like such as the ObjectInputStream and the data will be serialized correctly.

Similar Messages

  • Read Object Message using JMS Adapter

    Hi,
    My JMS queue receives an object message.I want to read that object message using JMS adapter.Currently the JMS Adapter payload type is given options to read only 'TextMessage','BytesMessage','MapMessage'.How to read ObjectMesage using this adapter?Please help me on this?

    Hi,
    As far as i know, JMS Object Messages is not supported by XI JMS adapter.
    you need to have the JMS provider to transform the message to bytes messages.
    (Refer to SAP note 856346)

  • Pls, Determine what file's encoding when read a file use NIO

    Hi every body,
    When I use NIO (New I/O JDK1.4) to read a file's content.
    How can I know exactly file's encoding (example: UTF-8, Cp1252, shift-jis ...) to choose right decoder to decode the file??
    Thanks
    Best regards.
    Hung, Nguyen Thanh.

    I think there's no way to do that except...
    If you are sure your files are all in japanese,
    you can use JISAutoDetect encoding.

  • How to write a (g)zip file to disk using NIO

    Hi,
    I want to write some data to a zipped file. I have all data to write to disk in ByteBuffer objects so I want to use NIO. The GZIPOutputstream does not have a getChannel() method. So what is the best method to zip data to file?
    Any comments are welcome!!
    Uli

    Sorry, wrong ByteBuffer in my claspath.
    So why don't you copy the bytes out of it using the get(byte[], int, int) ?

  • Passing object with NIO

    HI All
    I am trying to figure out if we can pass objects when using NIO.
    If anyone has any idea about this please let me know
    Thanks and Regards
    Pankaj Tiwari

    Very tricky. If you are in non-blocking mode you will have to prepend a length word. Generally the idea is to serialize the object to a ByteArrayOutputStream, then write its length and its data to the channel. At the other end, read the length word, then read that many bytes into a byte array, wrap that in a ByteArrayInputStream, then deserialize from that.

  • GZIP using nio ByteBuffer

    In Java 1.4 CharsetEncoder/CharsetDecoder classes were added to encode/decode unicode to/from ByteBuffers to fully utilize the performance advantages of the nio package. Why didn't they do the same for GZIP compresssion/decompression? Does anyone know of a way to read/write a GZIP file using nio and compress/decompress to/from ByteBuffers instead of using GZIPInputStream and GZIPOutputStream?

    llschumacher wrote:
    That will work but it is not what I had in mind. I wish to offload compression/decompression to another thread. Basically what I am doing is reading byte buffers with one thread, queueing them to a second thread to decompress and then queueing the decompressed buffer to a third thread for Unicode Decoding. I also want to use 3 threads in reverse order to perform writes. I can do this with Unicode encode/decode using CharsetEncoder/CharsetDecoder classes because they deal directly with ByteBuffers. Your solution would require me to use the same thread for IO and compress/decompress.here you go...
    1) create a threadpool executor.
    2) inherit from and extend callables to read or write nio channel objects
    3) use Inflate/Deflate on byte[] for your needs.
    4) works for JCE code as well

  • Dynamic Creation of Objects using Tree Control

    I am able to Create Dynamic Objets using List control in
    flex,but not able to create objects using TreeControl,currently iam
    using switch case to do that iam embedding source code please help
    me how to do that
    <?xml version="1.0" encoding="utf-8"?>
    <!--This Application Deals With How to Create Objects
    Dynamically -->
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute">
    <mx:XML id="treeDP">
    <node label="Controls">
    <node label="Button"/>
    <node label="ComboBox"/>
    <node label="ColorPicker"/>
    <node label="Hslider"/>
    <node label="Vslider"/>
    <node label="Checkbox"/>
    </node>
    </mx:XML>
    <mx:Script>
    <![CDATA[
    import mx.core.UIComponentGlobals;
    import mx.containers.HBox;
    import mx.controls.*;
    import mx.controls.VSlider;
    import mx.controls.Button;
    import mx.controls.Alert;
    import mx.core.UIComponent;
    import mx.controls.Image;
    import mx.managers.DragManager;
    import mx.events.DragEvent;
    import mx.controls.Tree;
    import mx.core.DragSource
    import mx.core.IFlexDisplayObject;
    /*This function accepts the item as on when it is dragged
    from tree Component */
    private function ondragEnter(event:DragEvent) : void
    if (event.dragSource.hasFormat("treeItems"))
    DragManager.acceptDragDrop(Canvas(event.currentTarget));
    DragManager.showFeedback(DragManager.COPY);
    return;
    else{
    DragManager.acceptDragDrop(Canvas(event.currentTarget));
    return;
    /*This Function creates objects as the items are Dragged
    from the TreeComponent
    And Creates Objects as and When They Are Dropped on the
    Container */
    private function ondragDrop(event:DragEvent) : void
    if (event.dragSource.hasFormat("treeItems"))
    var items:Array =event.dragSource.dataForFormat("treeItems")
    as Array;
    for (var i:int = items.length - 1; i >= 0; i--)
    switch(items
    [email protected]())
    case "Button":
    var b:Button=new Button();
    b.x = event.localX;
    b.y = event.localY;
    b.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
    myCanvas.addChild(b);
    break;
    case "ComboBox":
    var cb:ComboBox=new ComboBox();
    myCanvas.addChild(cb);
    cb.x = event.localX;
    cb.y = event.localY;
    cb.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
    break;
    case "ColorPicker":
    var cp:ColorPicker=new ColorPicker();
    myCanvas.addChild(cp);
    cp.x = event.localX;
    cp.y = event.localY;
    cp.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
    break;
    case "Vslider":
    var vs:VSlider=new VSlider();
    myCanvas.addChild(vs);
    vs.x = event.localX;
    vs.y = event.localY;
    vs.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
    break;
    case "Hslider":
    var hs:HSlider=new HSlider();
    myCanvas.addChild(hs);
    hs.x = event.localX;
    hs.y = event.localY;
    hs.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
    break;
    case "Checkbox":
    var check:CheckBox=new CheckBox();
    myCanvas.addChild(check);
    check.x = event.localX;
    check.y = event.localY;
    check.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
    break;
    else {
    var Component:UIComponent =
    event.dragSource.dataForFormat("items") as UIComponent ;
    Component.x = event.localX;
    Component.y = event.localY;
    Component.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
    myCanvas.addChild(Component);
    /*How to move the Objects within the Container */
    public function mouseMoveHandler(event:MouseEvent):void{
    var
    dragInitiator:UIComponent=UIComponent(event.currentTarget);
    var ds:DragSource = new DragSource();
    ds.addData(dragInitiator,"items")
    DragManager.doDrag(dragInitiator, ds, event);
    ]]>
    </mx:Script>
    <mx:Tree dataProvider="{treeDP}" labelField="@label"
    dragEnabled="true" width="313" left="0" bottom="-193" top="0"/>
    <mx:Canvas id="myCanvas" dragEnter="ondragEnter(event)"
    dragDrop="ondragDrop(event)" backgroundColor="#DDDDDD"
    borderStyle="solid" left="321" right="-452" top="0"
    bottom="-194"/>
    </mx:Application>
    iwant to optimize the code in the place of switch case
    TextText

    Assuming your objects are known and what you need are simply
    variable names created by the program, try using objects as
    associative arrays:
    var asArray:Object = new Object();
    for (var n:int = 0; n < 10; n++) {
    asArray["obj" + n] = new WHAT_EVER();

  • How to upload data into SAP BW Info Objects using SAP XI

    Hi,
    I need to upload master and hierarchy data into SAP BW Info Objects using SAP XI as EAI.
    Can anyone suggest me the best solution to do it.
    Thanks in Advance,
    Volker.

    Hi! Have you not checked the BW-XI Integration document? It is available on the main page of the SDN section for XI. Almost all the steps for the integration are there...

  • After zooming in on an object using arrow keys to nudge, it crashes most of the time

    After zooming in on an object, using arrow keys to nudge, it crashes most of the time.
    Versions:
    Illustrator CS6, latest update
    Mac OS X 10.9.4
    FontAgent Pro 6.2
    Troubleshooting I've tried
    -trashed all related Illus. preferences
    -updated the only plug-in being used (FontAgent Pro), to the latest
    -disabled all but absolutely necessary fonts
    -repaired both system and user permissions
    -quit all other apps, so that only Illus. running.
    -fonts verified
    Was never a problem until a couple weeks ago, so the obvious question is "what changed?".  The two things we changed in the time period that the crashing started, is we replaced a balky external drive with a new one, and started our TimeMachine backups over again. And #2, we updated to the latest CS6 versions (due to other quirky issues).
    One odd thing to point out...perhaps is "normal", but in the crash reports, it's reporting that Illustrator is 16.0.0, but "About Illustrator" shows that it's 16.2.2.
    Everything else running fine on this iMac -- no reason to suspect it's the operating system.
    Has anyone run into this bug? If so, what have you done to fix this?
    I've not seen anything like this mentioned in Adobe's update change logs or their troubleshooting info.

    -> go to View Menu -> Toolbars -> select "Navigation Toolbar"
    -> go to View Menu -> Zoom -> click "Reset"
    -> go to View Menu -> Page Style -> select "Basic Page Style"
    -> go Tools Menu -> Clear Recent History -> Time range to clear: select EVERYTHING -> click Details (small arrow) button -> place Checkmarks on ALL Options -> click "Clear Now"
    -> go to Help Menu -> select "Restart with Add-ons Disabled"
    Firefox will close then it will open up with just basic Firefox. Now
    -> go to Tools Menu -> Add-ons -> Extensions section -> REMOVE any Unwanted/Suspicious Extension (add-ons) -> Restart Firefox
    You can enable the Trustworthy Add-ons later. Check and tell if its working.

  • In Reply to : How to validate org.jdom.Document object using xsd: dvohra09

    Hi All
    I am creating org.jdom.Document object using constructor Document() and adding children using setRootElement(), setChildren() and addContent() methods. The children are objects of org.jdom.Element. If i want to validate the org.jdom.Document using xsd what i have to do. Thanks in anticipation.

    I tried the below code and it is always giving the
    Parsing fatal error : The markup in the document preceding the root element must be well-formed.
    But it is possible to validate the same Document object as right document after writing it onto xml file using XMLOutputter and parsing it using DOMParser
    Thanks in anticipation
    org.jdom.Document document;
    String documentString=document.toString();
    StringReader stringReader=new
    StringReader(documentString);
    SAXBuilder saxBuilder =new
    SAXBuilder("org.apache.xerces.parsers.SAXParser",true);
    saxBuilder.setFeature("http://xml.org/sax/features/vali
    ation",  true);
    saxBuilder.setFeature("http://apache.org/xml/features/v
    lidation/schema",  true);
    saxBuilder.setFeature("http://apache.org/xml/features/v
    lidation/schema-full-checking", true);
    //Set a error handler with
    setErrorHandler(org.xml.sax.ErrorHandler errorHandler)
    saxBuilder.build(stringReader);

  • Server hangs up when tryin to read object Urgent Help Plz

    Hi,
    I've been working on a client-server model for a while, I've tested my applicaction a thousand of times locally (I mean, server and serveral clients running on the same machine) and it's ok, now I finally run server in a remote host and I find it rarely works fine, most of the times server hangs up when tryin to read objects I dont know why.
    this is the part of the server-code where the problem begins:
    public int EscucharSocket(){
            Socket cliente = null;
            System.out.println("Servidor en escucha...\n");
            while(true){
                try{
                    cliente = SocketS.accept();
                    //I get client's ip and port
                    String ip = cliente.getInetAddress().getHostAddress();
                    int puerto = cliente.getPort();
                    //After the conexion is made, server reads a signature to
                    //identify the client
                   //in function process I check if the signature is valid
                   //SignedData is a class where I wrap the signiture (obviously
                   //it implements Serializable interface
                   process((SignedData)le.LeerObject(cliente));
                   //Other things done here
                catch (Exception e) { }
    }le is a class I use to read,write data to the socket, this is the code of the LeerObject function
    public Object LeerObject(Socket c) throws Exception {
           //Here Is where the server hangs up
            ObjectInputStream b = new ObjectInputStream(c.getInputStream());
            return b.readObject();
    }As I wrote when running locally, there is no problem, but when I have a remote host, that happens
    Any help or idea?

    Hi again, thnx for your help
    I modified my LE class so I just create a couple of Input/Output Streams per client (on server n client program), this is now the complete code of the class:
    import java.net.*;
    import java.io.*;
    public class LE {
        DataOutputStream     dos;
        ObjectOutputStream  oos;
        DataInputStream        dis;
        ObjectInputStream     ois;
        //Streams are created just once in the constructor
        public LE (Socket s) throws Exception {
            dos = new DataOutputStream(s.getOutputStream());
             //I'm not sure if this flush has any sense
            dos.flush();
            oos = new ObjectOutputStream (s.getOutputStream());
            oos.flush();
            dis = new DataInputStream(s.getInputStream());
            ois = new ObjectInputStream (s.getInputStream());
        public void EscribirByte(byte datos[],int len) throws Exception {
            dos.write(datos,0,len);
            dos.flush();
        public void EscribirString(String dato) throws Exception {
            dos.writeUTF(dato);
            dos.flush();
        public void EscribirChar(char dato) throws Exception {
            dos.writeChar(dato);
            dos.flush();       
        public void EscribirInt(int dato) throws Exception {
            dos.writeInt(dato);
            dos.flush();
        public void EscribirLong(long dato) throws Exception {
            dos.writeLong(dato);
            dos.flush();
        public void EscribirObject(Object dato) throws Exception {
            oos.writeObject(dato);
            oos.flush();
        public String LeerString() throws Exception {       
            return dis.readUTF();
        public int LeerInt() throws Exception {       
            return dis.readInt();
        public char LeerChar() throws Exception {       
            return dis.readChar();
        public long LeerLong() throws Exception {       
            return dis.readLong();
        public Object LeerObject() throws Exception {       
            return ois.readObject();
    }part of code of server and client, where the conexion is made and the LE object is created
    Server:
    try{
           cliente = SocketS.accept();               
           //After accepting the conexion the LE object is created
            le = new LE(cliente);
            //I get client's ip and port
            String ip = cliente.getInetAddress().getHostAddress();
            int puerto = cliente.getPort();
            //Object wraping signature is read        
            process((SignedData)le.LeerObject());
            //other control operations doing here
            //A thread is created to receive requests from client
            //(reference to LE object is passed to the thread
           ConexionCliente c = new ConexionCliente (cliente,id_persona,id_grupo,tipo_usuario,backup,le);                               
            //thread is started
            c.start();
    catch (Exception e) {
        try {
            cliente.close();
        catch(Exception e2){}
    }Cliente code:
    try{
       //it connects to the server
       c=new Socket(host,puerto);
       //After accepting the conexion the LE object is created         
       le = new LE(c);
       //other things made here to genarate SignedData Object
      //It sends signed data object
      le.EscribirObject(Data);          
      //A thread is created and started to receive messages from server
      //reference to object LE is sent to the thread to avoid the need of
      //creating another
      new ConexionServidorClient(c,id_persona,ci,le).start();
      return 1;
    catch(Exception e) {
       return -1;
    }after the change, itworks a little better, but still most of the times server hangs up, I can't make server operational yet and I dont have any idea for solving this issue

  • How can i get the value stored in the session object using its sessionid

    how can i get the value stored in the session object using its sessionid by running stand alone java application

    myforum wrote:
    how can i get the value stored in the session object using its sessionid by running stand alone java applicationThis does not seem to make sense! You need at least to give a lot more detail of what you are doing.

  • Rendering the PDF page to Bitmap object using Acrobat SDK DrawEx() or CopyToClipboard()

    I am trying to find whether each page in PDF document is color or monochrome.
    For doing this I am rendering the PDF page to Bitmap object using Acrobat SDK DrawEx() or CopyToClipboard()
    Once after rendering the PDF page, I am using GetPixel() to read each pixel value to decide about color or Monochrome.
    Problem:
    When I read the pixel to decide about the page color or monochorme, in some XP machines it is showing the PDF page as color and in some PC it is showing it as Monochrome.  Color quality in both the system is kept as 32 Bit.
    After this I tried copying the PDF page directly into clipboard and then take the clipboard image to decide about color and monochorme, but even this also behaves in the similar way.
    Question:
    Why rendering the PDF page to Bitmap object using DrawEx() or CopyToClipboard() is behaving differently in each machines.
    If required I will send my sample project.
    With regards,
    Rajeshrv.

    In SDK documentation, there is no methods are defined for getting the color of the page.  In color spaces and color values, we can set the color for drawing operations. A method AVPageViewSetColor is used for setting the color. 
    But there is no methods defined for getting the color in the page.  Please let me know , is there any alternative way.
    Thanks in advance.

  • What is the steps to send a send a soap object using jms in websphere 6.1

    Hi, can anybody help me out ..i am reaally new to jms and soap
    i had gone through this link http://docs.sun.com/app/docs/doc/819-7757/6n9mar6iv?a=view
    where i got some information regarding how to recieve and send soap object using ....
    but my problem how i will look up ...if i use javax.jms.QueueConnectionFactory and QueueSeesion....while converting the soap message to jms message its getting failed in websphere 6.1 ..... whether i have to use this com.sun.messaging.QueueConnectionFactory instead of this javax.jms.QueueConnectionFactory ...or how to process it
    can anybody help me wat are steps followed while sending a soap message to queue and replying it back. using websphere6.1 or provide me some link so i go through pls help me out???
    Thanks in advance..

    Hi, can anybody help me out ..i am reaally new to jms and soap
    i had gone through this link http://docs.sun.com/app/docs/doc/819-7757/6n9mar6iv?a=view
    where i got some information regarding how to recieve and send soap object using ....
    but my problem how i will look up ...if i use javax.jms.QueueConnectionFactory and QueueSeesion....while converting the soap message to jms message its getting failed in websphere 6.1 ..... whether i have to use this com.sun.messaging.QueueConnectionFactory instead of this javax.jms.QueueConnectionFactory ...or how to process it
    can anybody help me wat are steps followed while sending a soap message to queue and replying it back. using websphere6.1 or provide me some link so i go through pls help me out???
    Thanks in advance..

  • Problem reading objects

    Hi i am trying to read objects from i file i have written them to but cannot seem to get it goint any suggestions here are two errors but i am sure their are more
    ---------- javac ----------
    C:\university_class_work\cosc1309\Assignments\Assignment1\Bin2Text.java:26: incompatible types
    found : java.lang.Object
    required: java.io.ObjectInputStream
    while ((ins = ins.readObject()) != null) {
    ^
    C:\university_class_work\cosc1309\Assignments\Assignment1\Bin2Text.java:32: cannot resolve symbol
    symbol : method flush ()
    location: class java.io.ObjectInputStream
    ins.flush ();
    ^
    2 errors
    Normal Termination
    Output completed (1 sec consumed).
    import java.util.*;
    import java.text.*;
    import java.io.*;
    // Bin2Text.java
    // Assignment1
    // Created by dragon on Sun Mar 09 2003.
    // Copyright (c) 2003 __MyCompanyName__. All rights reserved.
    public class Bin2Text implements Serializable {
    public static void main(String[] args) throws IOException{
    String name;
    //PrintWriter out = null;
    Text2Bin p2b = new Text2Bin();
    StringTokenizer words = null;
    String line;
    try {
    PrintWriter out = new PrintWriter (new BufferedWriter (new FileWriter ("out.txt")));
    FileInputStream in = new FileInputStream ("in.bin");
    ObjectInputStream ins = new ObjectInputStream (in);
    while ((ins = ins.readObject()) != null) {
    PizzaEater myPizzaEater = new PizzaEater();
    ins.readObject(myPizzaEater);
    out.write (myPizzaEater);
    ins.reset ();
    ins.flush ();
    ins.close();
    out.close ();
    catch (IOException ioe) {
    System.out.println(ioe.getMessage());
    catch (NegativeNumberException nne) {
    System.out.println ("NegativeNumberException message was: " +
    nne.getMessage());
    class NegativeNumberException extends Exception {
    * Default constructor setting NegativeNumberException to the default
    * as specified by API reference Exception
    public NegativeNumberException () {
    super();
    * a Constructor passing the number value of the exception and
    * returning it with feedback
    public NegativeNumberException (int slices) {
    super("Number entered: " + slices + " number must be positive.");
    }

    Hi i am trying to read objects from i file i have
    written them to but cannot seem to get it goint any
    suggestions here are two errors but i am sure their
    are more
    ---------- javac ----------
    C:\university_class_work\cosc1309\Assignments\Assignmen
    1\Bin2Text.java:26: incompatible types
    found : java.lang.Object
    required: java.io.ObjectInputStream
    while ((ins = ins.readObject()) != null) {
    ^I'm not sure what you're trying to do exactly, I think its retrieve the next object from ObjectInputStream, you'd probably want to use another variable of type Object
    C:\university_class_work\cosc1309\Assignments\Assignmen
    1\Bin2Text.java:32: cannot resolve symbol
    symbol : method flush ()
    location: class java.io.ObjectInputStream
    ins.flush ();
    ^
    2 errors
    Normal TerminationNo flush() for InputStream objects.
    Output completed (1 sec consumed).
    import java.util.*;
    import java.text.*;
    import java.io.*;
    // Bin2Text.java
    // Assignment1
    // Created by dragon on Sun Mar 09 2003.
    // Copyright (c) 2003 __MyCompanyName__. All rights
    reserved.
    public class Bin2Text implements Serializable {
    public static void main(String[] args) throws
    ws IOException{
    String name;
    //PrintWriter out = null;
    Text2Bin p2b = new Text2Bin();
    StringTokenizer words = null;
    String line;
    try {
    PrintWriter out = new PrintWriter (new
    r (new BufferedWriter (new FileWriter ("out.txt")));
    FileInputStream in = new FileInputStream
    Stream ("in.bin");
    ObjectInputStream ins = new ObjectInputStream
    Stream (in);
    while ((ins = ins.readObject()) != null) {
    PizzaEater myPizzaEater = new
    Eater = new PizzaEater();
    ins.readObject(myPizzaEater);
    out.write (myPizzaEater);
    ins.reset ();
    ins.flush ();
    ins.close();
    out.close ();
    catch (IOException ioe) {
    System.out.println(ioe.getMessage());
    catch (NegativeNumberException nne) {
    System.out.println ("NegativeNumberException
    xception message was: " +
    nne.getMessage());
    class NegativeNumberException extends Exception {
    * Default constructor setting
    ing NegativeNumberException to the default
    * as specified by API reference Exception
    public NegativeNumberException () {
    super();
    * a Constructor passing the number value of the
    the exception and
    * returning it with feedback
    public NegativeNumberException (int slices) {
    super("Number entered: " + slices + " number must
    st be positive.");

Maybe you are looking for

  • Jukebox Zen Xtra turns itself off and

    The battery is dead. when I plug it in to charge it turns itself on, the Creative copyright screen loads up, then the EAX screen loads up then it turns itself off. second later it turns itself back on and the process is repeated. Is there any way to

  • When using my iMac the screen judders momentarily

    Mu imac screen judders, freezes momentarily then goes back to normal. Annoying more than anything but I ask whether this cd be anything potentially serious?

  • Certification expired? @ HelloWorld-app.xml in tutorial pdf

    Hi, everyone. Im just a student passed by and interesting in Flex app (however i dont have a good fundamental about web ^^") I tries to follow the pdf file, devappsflex. Using Notepad++ as texteditor and FlexSDK in Vista sp1 64bit. HelloWorld.mxml is

  • Building and deploying petstore

    I've made a change to the petstore example (in CatalogDAO.java) and I'd like to rebuild and deploy it. Can you tell me how I can do it. I've tried a few different things but I continue to get the original version. Thanks

  • Code being moved around after editing in Design View

    Hello all, Call me a neat freak, a OCD guy, whatever, I don't care. I primarily work in code view and when I do, I like to have my tags in a nice, neat, order. It didn't do this in DW8 but it does this in DW CS3, but I've noticed that ANY time I make