ObjectOut/InputStream problem

I have a problem on writing objects to a binary file. Let say, everytime the writeOBJ button is triggered in main program, "public void writePet(PetRecord newPet)" is invoked and the passing object is written to the ObjectOutputstream.
The problem is, it is writing the same object over and over again eventhough the passing objects are different.
(I make sure the passing objects are dfferent.)
Also, appending is not working too....eventhough i said
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("filename.records",true));
the followindg is part of my code.....
import java.io.*;
import java.util.*;
import javax.swing.*;
public class MyFile
     private static int index = 0;
     private ObjectInputStream inputStream = null;
     private ObjectOutputStream outputStream = null;
     private Vector<PetRecord> readPetV = new Vector<PetRecord>(30);
     //private Vector<PetRecord> writePetV  = new Vector<PetRecord>(30);
     private boolean flagOutput = false;
     private boolean flagInput = false;
     public boolean getOutputflag()
          return flagOutput;
     public boolean getInputFlag()
          return flagInput;
     public int getIndex()
          return index;
     @SuppressWarnings("unchecked")
     public Vector<PetRecord> getReadPetV()
          return(Vector<PetRecord>)readPetV.clone();
//==============================================================================================
     //Method for creating new file.
          public void connectToOutputFile()
               boolean newFile = false;
               do{
                    try
                         String fileName = JOptionPane.showInputDialog(null,
                                   "Please Enter the New file name","FileName.records");
                         File fileObject = new File(fileName);
                         if(!fileObject.exists())
                              outputStream = new ObjectOutputStream(new FileOutputStream(fileName.trim()));
                              newFile = true;
                              flagOutput = true;
                         else
                              JOptionPane.showMessageDialog(null,"File "+ fileName +" is already exist.");
                              newFile = false;
                              flagOutput = false;
                    catch (IOException exp)
                         JOptionPane.showMessageDialog(null,"Error Opening output file.");
                         newFile = false;
                         flagOutput = false;
               }while(!newFile);
//==============================================================================================
     //opening the input file for the display
          public void connectToInputFile()
               boolean inputError = true;
               String inputFileName = null;
               do
                    inputFileName = JOptionPane.showInputDialog(null,
                              "Please Enter the File name to Read from","FileName.records");
                    inputFileName = inputFileName.trim();
                    try
                         inputStream = new ObjectInputStream(new FileInputStream(inputFileName));
                         outputStream = new ObjectOutputStream(new FileOutputStream(inputFileName, true));
                         inputError  = false;
                         flagInput = true;
                         flagOutput = true;
                    catch(FileNotFoundException exp)
                         JOptionPane.showMessageDialog(null,"File "+inputFileName+" not found.");
                         inputError = true;
                         flagInput = false;
                    catch(IOException e)
                         JOptionPane.showMessageDialog(null,"Error Opening Input file"
                                   +inputFileName);
                         inputError = true;
                         flagInput = false;
               }while(inputError);
//==============================================================================================
     public void writePet(PetRecord newPet)
               try
                    outputStream.writeObject((PetRecord)newPet);
                    outputStream.flush();
               catch(IOException e)
                    JOptionPane.showMessageDialog(null,"Error writing to file.");
                    System.exit(0);
          public void writePet(PetRecord newPet)
               writePetV.addElement(newPet);
          public void writePetV()
               for(int i=0; i < writePetV.size(); i++)
                    try {
                         outputStream.writeObject((PetRecord)writePetV.elementAt(i));
                    } catch (IOException e) {
                         // TODO Auto-generated catch block
                         e.printStackTrace();
//==============================================================================================
//read method for reading the object from the file
          public void readData()
               //reading the objects datas from file
               PetRecord readNext;
               try
                    while((readNext = (PetRecord)inputStream.readObject()) != null)
                         readPetV.addElement((PetRecord)readNext);
                         System.out.println(readNext.getName());
               catch (Exception e)
                    //JOptionPane.showMessageDialog(null,"End of record");
               index = readPetV.size();
//==============================================================================================
//     method for closing files.
          public void closeFile()
               if (flagOutput)
                    try
                         outputStream.close();
                    catch(IOException e)
                         JOptionPane.showMessageDialog(null, "Error Closeing file"
                                   + e.getMessage());
                         System.exit(0);
                    catch(NullPointerException empty)
                         JOptionPane.showMessageDialog(null,"There is nothing to close. DUHH!!!!");
               if (flagInput)
                    try
                         inputStream.close();
                    catch(IOException e)
                         JOptionPane.showMessageDialog(null, "Error Closeing file"
                                   + e.getMessage());
                         System.exit(0);
                    catch(NullPointerException empty)
                         JOptionPane.showMessageDialog(null,"There is nothing to close. DUHH!!!!");
[/code]

Ok! I think i solved the problem. In the main program I used one major object to pass through to the write() method. let's say constructed an PetRecord object and everytime I wanna add user input, I used "mutators" (set methods) of that Object and pass to the write(PetRecord newPet) method. It seems that eventhough the new values were taken by the newPet Object, it stills wirte the old one to the object stream. I don't know why that happen.
So, what i did is, every time i want to add user input, I create a new Object of PetRecord class and it works fine.
Does anybody have any idea why that happen???
but appeending to a file still doesn't work though!!! I'm trying to fix it....

Similar Messages

  • Parsing from InputStream problem

    I have a serious problem with parsing XML from an InputStream.
    It is the exact same problem other people had before in those threads :
    http://forum.java.sun.com/thread.jsp?forum=34&thread=343710
    http://forum.java.sun.com/thread.jsp?forum=34&thread=68180
    http://forum.java.sun.com/thread.jsp?forum=34&thread=68259
    I have read the FAQ at http://www.jdom.org/docs/faq.html which suggest the following :
    byte[] buf = new byte[length];
    new DataInputStream(inputStream).readFully(buf);
    InputStream in = new ByteArrayInputStream(buf);
    (Contributed by Joseph Bowbeer)
    But my problem still remains the same. What happens if more than 1 XML documents were writen in the InputStream because the writting took place very fast and the receiver could not parse the XML document fast enough so now the byte buffer 'buf' contains 2 XML documents one after the other ? What if it contains half XML document because the sender was temporarily blocked or something; and after some time it continues with the rest XML document ?
    how could I overcome those problems ?
    thanks

    The root cause of the problems reported in this and other threads seems to be the SAX parsers are buffering the entire input stream before they commence parsing (which appears to be completely contrary to the spirit of SAX). This explains the parser hanging behaviour reported by some folk. It also explains why the parsers are awaiting for some sort of EOF marker before they begin parsing.
    Maybe this buffering behaviour has been fixed in the newer releases of xerces and crimson et al, but there is a good discussion of this problem and a solution (albeit for xerces), at http://xml.apache.org.xerces-j/faq-write.html, under the section "how do I read data from a stream as it arrives?".

  • InputStream problem with Runtime.exec

    Dear all,
    I am writing a java application which is executing an external program (through threads). I am trying to read the output of that program while is in execution. Anyway i found out that InputStreamReader is not ready unless enough output of program is coming or the program exits.
    I simplified things writing the following small C program:
    main(){
    printf("Just a print\n");
    for(;;){} //Or anything that might keep program in execution
    So i am trying to find out why i cant get the output of this program unless it exits. Is this a problem with the underlying Stream? Is there any workaround?
    Thanks for any help.

    You are right. The C code is that of an external program that i am trying to execute and get its output. Actually i am working on a bigger program that it prints Directories recursively. To keep things simpler i used that simple C program to explain my problem.
    The code i am using is the following:
    /* WindowsExec.java */
    import java.io.*;
    public class WindowsExec
         response std_out,std_err;
         public WindowsExec(){
         try{
         String[] cmd = new String[]{"dark.exe"};
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(cmd);
    std_out = new response(proc.getInputStream(),System.out);          std_err = new response(proc.getErrorStream(),System.err);
    std_out.start();
         std_err.start();     
    int exitVal = proc.waitFor();
    System.out.println("ExitValue: " + exitVal);
                   proc.destroy();
         } catch (Throwable t){
              t.printStackTrace();
    public static void main(String args[]){
              new WindowsExec();
    /* Response.java */
    import java.io.*;
    class response extends Thread
         InputStream is;
         PrintStream type;
         public response(InputStream is, PrintStream type){
              this.is = is;
              this.type = type;
         public void run(){
         try{
              InputStreamReader isr = new InputStreamReader(is);
    while(true){
    if(isr.ready()){
    System.out.println("Its ready!"); //HERE!!!
              break;     
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    while ( (line = br.readLine()) != null){
    System.out.println(line);
                   isr.close();
                   is.close();
              catch (Exception ioe){
    ioe.printStackTrace();
    Notice that i am never getting isr.ready() = true!

  • SAXParser InputStream problem - URGENT

    hi
    i'm trying to parse a a xml document as an inputstream, but every time i try to compile the code the following error appears:
    "Incompatible type for method. Can't convert java.io.InputStream to java.lang.String".
    the parse constructor as an inputstream input parameter. i don't know why this error happens.
    the code is something like this:
    Parser parser = new SAXParser();
    InputStream is =null;
    parser.setDocumentHandler(sample);
    parser.setEntityResolver(sample);
    parser.setDTDHandler(sample);
    parser.setErrorHandler(sample);
    //some code
    //texto_xml is a CLOB variable
    is = texto_xml.getAsciiStream();
    parser.parse(is);
    can someone help me?
    thanks in advanced

    Also, use the factory to get your SAX Parser instance:
    SAXParserFactory factory=SAXParserFactory.newInstance();
    factory.setValidating( true ); //set true to validate content against DTD
    SAXParser parser = factory.newSAXParser();

  • Inputstream problem

    I have written a server and a client,the client send string "single" or "continuous".when "single" is sent, the client recives a single string,when a continuous is sent sent it must recive continuously ,
    but it does not recieve continuous values from the server.Is it because i did not allocate much space to the outputline variable
    the server gets its values from a different program.
    client
    import java.io.*;
    import java.net.*;
    public class CDATCPClient {
         public static void main(String[] args) throws IOException {
              Socket kkSocket = null ;
              PrintWriter out = null;
              BufferedReader in = null;
              try {
              // Open Client Socket for connection to Server
                   kkSocket = new Socket("localhost",4444);
                   //Output Stream to send values to Server
                   out = new PrintWriter(kkSocket.getOutputStream(),true);
                   //Input Stream to recieve values from Server
                   in = new BufferedReader(new BufferedReader(new InputStreamReader(kkSocket.getInputStream())));
              } catch (UnknownHostException e) {
                   System.err.println("Dont know host : WSNSYSTEM");
                   System.exit(-1);
              } catch (IOException e) {
                   System.err.println("Couldnt get I/O for the connection to : WSNSYSTEM");
                   System.exit(-1);
    //Stream for Input From console
    //Input can only be single ,continuous or bye
              BufferedReader stdIn = new BufferedReader(new BufferedReader(new InputStreamReader(System.in)));
              String fromServer; //To get input from server to this variable
              String fromUser; //To get input from command line ,and send to Server for processing
              while ((fromServer = in.readLine()) != null) {
                   System.out.println("The Values received (values seperated by : and the group is seperated by :: )" + " \n " + fromServer);
                   fromUser = stdIn.readLine(); //input from user command line
                   if(fromUser != null){
                        System.out.println("User input given is: " + fromUser);               
                        out.println(fromUser);// Send user input to server
                   if(fromUser != null && fromUser.equalsIgnoreCase("bye"))                    
                        break;
    #'##############################server     ############################
    import java.io.*;
    import java.net.*;
    public class CDATCPServer {
    public static void main(String args[]) {
         ServerSocket serverSocket = null; //Server Socket
         String inputLine = null, outputLine = null;
    try {
         try {
    serverSocket = new ServerSocket(4444);
    catch (IOException e) {
    System.out.println("Could not listen on port: 4444");
    System.exit(-1);
    Socket clientSocket = null;//Socket for communicating with the client
    try {
    clientSocket = serverSocket.accept();
    catch (IOException e)
    System.out.println("Accept failed: 4444");
    System.exit(-1);
    // out is the Stream to send data to the client
         PrintWriter out = new PrintWriter ( clientSocket.getOutputStream(), true);
         //in is the Stream to receive data from Client
         BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    // a new instance of the CDATCPProtocol class
    CDATCPProtocol ctp = new CDATCPProtocol();     
         //###################### BootStrapping Phase of the WSN
         ctp.executeServiceRequest("bstrap");
         outputLine = ctp.getCdaEncryptedValuesReceived();
         if (outputLine != null)          
                   outputLine += "::" + ctp.getCdaResponseReceived();
              else
                   outputLine = "null::" + ctp.getCdaResponseReceived();
              System.out.println("Bootstrapping Phase");     
              out.println(outputLine);
              out.flush();
              /* The values coming from the client can be single or continuous depending upon the request
              if it is "single" , a single set of values is sent to the client,where as if the input is
              "continuous" , continuous messages are sent from the server to the client */
              while((inputLine = in.readLine()) != null)
              //for Single Request from the sink
              if(inputLine.equalsIgnoreCase("single"))
                        ctp.executeServiceRequest(inputLine);
                        outputLine = ctp.getCdaEncryptedValuesReceived();
                   if (outputLine != null)          
                             outputLine += "::" + ctp.getCdaResponseReceived();
                        else
                             outputLine = "null::" + ctp.getCdaResponseReceived();               
                        out.println(outputLine);
                        out.flush();
                   else if(inputLine.equalsIgnoreCase("continuous"))
                        //For Continuous Values from the sink
                        ctp.executeServiceRequest(inputLine);
                        outputLine = ctp.getCdaEncryptedValuesReceived();
                   if (outputLine != null)          
                             outputLine += "::" + ctp.getCdaResponseReceived();
                        else
                             outputLine = "null::" + ctp.getCdaResponseReceived();
                        out.println(outputLine);
    out.flush();
                   else if(inputLine.equalsIgnoreCase("Bye"))
                   {     // To Stop values coming from the sink
                   ctp.cdaStopsink();
                        break;     
                   else {
                        outputLine = "You are supposed to give the values : single or continuous or bye";      
                        out.println(outputLine);
                   out.flush();
              out.flush();
         out.close();
         in.close();     
         clientSocket.close();     
         serverSocket.close();
         }catch (IOException e)
    e.printStackTrace();
         i am also not sure if there is to be given an extra loop to be given at the Server,can u please help ?

    I have written a server and a client,the client send
    string "single" or "continuous".when "single" is
    sent, the client recives a single string,when a
    continuous is sent sent it must recive continuously
    but it does not recieve continuous values from the
    server.Is it because i did not allocate much space to
    the outputline variable
    the server gets its values from a different program.
    client
    import java.io.*;
    import java.net.*;
    public class CDATCPClient {
    public static void main(String[] args) throws
    s IOException {
              Socket kkSocket = null ;
              PrintWriter out = null;
              BufferedReader in = null;
              try {
                 // Open Client Socket for connection to Server
                   kkSocket = new Socket("localhost",4444);
                    //Output Stream to send values to Server
    out = new
    new PrintWriter(kkSocket.getOutputStream(),true);
    //Input Stream to recieve values from Server
    ver      
    in = new BufferedReader(new BufferedReader(new
    new InputStreamReader(kkSocket.getInputStream())));
              } catch (UnknownHostException e) {
                   System.err.println("Dont know host : WSNSYSTEM");
                   System.exit(-1);
              } catch (IOException e) {
    System.err.println("Couldnt get I/O for the
    the connection to : WSNSYSTEM");
                   System.exit(-1);
    //Stream for Input From console
    //Input can only be single ,continuous or bye
    BufferedReader stdIn = new BufferedReader(new
    ew BufferedReader(new
    InputStreamReader(System.in)));
    String fromServer; //To get input from server to
    to this variable
    String fromUser;   //To get input from command line
    ne ,and send to Server for processing
              while ((fromServer = in.readLine()) != null) {
    System.out.println("The Values received (values
    ues seperated by : and the group is seperated by ::
    )" + " \n " + fromServer);
    fromUser = stdIn.readLine(); //input from user
    ser command line
                   if(fromUser != null){
    System.out.println("User input given is: " +
    " + fromUser);               
    out.println(fromUser);// Send user input to
    t to server
    if(fromUser != null &&
    && fromUser.equalsIgnoreCase("bye"))                    
                        break;
              }> #'##############################server     ###############
    import java.io.*;
    import java.net.*;
    public class CDATCPServer {
    public static void main(String args[]) {
    ServerSocket serverSocket = null; //Server Socket
    ket
          String inputLine = null, outputLine = null;
    try {
           try {
    serverSocket = new ServerSocket(4444);
    catch (IOException e) {
    System.out.println("Could not listen on
    ot listen on port: 4444");
    System.exit(-1);
    Socket clientSocket = null;//Socket for
    et for communicating with the client
    try {
    clientSocket = serverSocket.accept();
    catch (IOException e)
    System.out.println("Accept failed: 4444");
    System.exit(-1);
    // out is the Stream to send data to the
    to the client
    PrintWriter out = new PrintWriter (
    iter ( clientSocket.getOutputStream(), true);
           //in is the Stream to receive data from Client
    BufferedReader in = new BufferedReader(new
    new
    InputStreamReader(clientSocket.getInputStream()));
    // a new instance of the CDATCPProtocol class
    CDATCPProtocol ctp = new CDATCPProtocol();     
    //###################### BootStrapping Phase of the
    e WSN
             ctp.executeServiceRequest("bstrap");
    outputLine =
    ine = ctp.getCdaEncryptedValuesReceived();
             if (outputLine != null)          
    outputLine += "::" +
    :" + ctp.getCdaResponseReceived();
               else
    outputLine = "null::" +
    :" +  ctp.getCdaResponseReceived();
               System.out.println("Bootstrapping Phase");     
               out.println(outputLine);
               out.flush();
    /* The values coming from the client can be single
    gle or continuous depending upon the request
    if it is "single" , a single set of values is sent
    ent to the client,where as if the input is
    "continuous" , continuous messages are sent from
    rom the server to the client */
              while((inputLine = in.readLine()) != null)
                //for Single Request from the sink
                  if(inputLine.equalsIgnoreCase("single"))
                              ctp.executeServiceRequest(inputLine);
    outputLine =
    putLine = ctp.getCdaEncryptedValuesReceived();
                           if (outputLine != null)          
    outputLine += "::" +
    = "::" + ctp.getCdaResponseReceived();
                              else
    outputLine = "null::" +
    ull::" +  ctp.getCdaResponseReceived();               
                             out.println(outputLine);
                             out.flush();
    else
    else if(inputLine.equalsIgnoreCase("continuous"))
                         //For Continuous Values from the sink
                            ctp.executeServiceRequest(inputLine);
    outputLine =
    tLine = ctp.getCdaEncryptedValuesReceived();
                          if (outputLine != null)          
    outputLine += "::" +
    "::" + ctp.getCdaResponseReceived();
                            else
    outputLine = "null::" +
    l::" +  ctp.getCdaResponseReceived();
                           out.println(outputLine);
    out.flush();
                    else if(inputLine.equalsIgnoreCase("Bye"))
                       {     // To Stop values coming from the sink
                          ctp.cdaStopsink();
                            break;     
                    else {
    outputLine = "You are supposed to give the
    e the values : single or continuous or bye";      
                         out.println(outputLine);
                       out.flush(); 
               out.flush();
             out.close();
             in.close();        
             clientSocket.close();     
             serverSocket.close();
             }catch (IOException e)
    e.printStackTrace();
    }> i am also not sure if there is to be given an
    en an extra loop to be given at the Server,can u
    please help ?

  • How to read und hash files!?

    Hi...
    I'm facing some "InputStream" problems.
    I want to hash files which is successful if files are < ~50MB. Here's my code...
    long length = file.length();
    InputStream in = new BufferedInputStream(new FileInputStream(file));
                   byte[] message = new byte[(int)length];
                    int offset = 0;
                      int numRead = 0;
                      while (offset < message.length
                             && (numRead=in.read(message, offset, message.length-offset)) >= 0)
                          offset += numRead;
    MessageDigest md = MessageDigest.getInstance("MD5");
    hash = md.digest(message);
    * toHexString
    **When I choose a file which is larger than 50 MB I get the following error:
    Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space
    I know what that error means and what could solve this but not how.

    Have a look at the class java.security.DigestInputStream.

  • Problem with Thread and InputStream

    Hi,
    I am having a problem with threads and InputStreams. I have a class which
    extends Thread. I have created and started four instances of this class. But
    only one instance finishes its' work. When I check the state of other three
    threads their state remains Runnable.
    What I want to do is to open four InputStreams which are running in four
    threads, which reads from the same url.
    This is what I have written in my thread class's run method,
    public void run()
         URL url = new URL("http://localhost/test/myFile.exe");
    URLConnection conn = url.openConnection();
    InputStream istream = conn.getInputStream();
    System.out.println("input stream taken");
    If I close the input stream at the end of the run method, then other threads
    also works fine. But I do not want to close it becuase I have to read data
    from it later.
    The file(myFile.exe) I am trying to read is about 35 MB in size.
    When I try to read a file which is about 10 KB all the threads work well.
    Plz teach me how to solve this problem.
    I am using JDK 1.5 and Win XP home edition.
    Thanks in advance,
    Chamal.

    I dunno if we should be doing such things as this code does, but it works fine for me. All threads get completed.
    public class ThreadURL implements Runnable
        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
        public void run()
            try
                URL url = new URL("http://localhost:7777/java/install/");
                URLConnection conn = url.openConnection();
                InputStream istream = conn.getInputStream();
                System.out.println("input stream taken by "+Thread.currentThread().getName());
                istream.close();
                System.out.println("input stream closed by "+Thread.currentThread().getName());
            catch (MalformedURLException e)
                System.out.println(e);
                //TODO Handle exception.
            catch (IOException e)
                System.out.println(e);
                //TODO Handle exception.
        public static void main(String[] args)
            ThreadURL u = new ThreadURL();
            Thread t = new Thread(u,"1");
            Thread t1 = new Thread(u,"2");
            Thread t2 = new Thread(u,"3");
            Thread t3 = new Thread(u,"4");
            t.start();
            t1.start();
            t2.start();
            t3.start();
    }And this is the o/p i got
    input stream taken by 2
    input stream closed by 2
    input stream taken by 4
    input stream closed by 4
    input stream taken by 3
    input stream closed by 3
    input stream taken by 1
    input stream closed by 1
    can u paste your whole code ?
    ram.

  • Problem with InputStream in a MIDlet

    I am doing some client/server networking using a socket connection in a MIDlet.
    When I make the socket connection I get a 220 reply.
    i.e "220 smtp.comcast.net"
    I read the status code from that response and then send the server my next command. (HELO). so far so good.
    The server returns a status code of 250. I can see that in my packet sniffer. again, this is a good thing.
    The problem is with my input stream. When I last read the input stream ch = is.read();
    the input stream didn't empty itself.
    So every time I get a response from the server, it appends to the last input I had.
    in this case:
    "220 smtp.comcast.net 250 comcast.net".
    I only expect to see:
    "250 comcast.net"
    I've tried is.close() and then reopening it when I expect a response from the server. This does not flush it.
    What can I do to rectify this?
    Thanks in advance,
    Mike

    or better, use a buffer to write to and give the number of read bytes to it:
    InputStream is; // from somewhere else in the MIDlet
    String rec;
    StringBuffer sb = new StringBuffer();
    byte[] buf = new byte[1024];
                   while( (c=is.read(buf)) != -1 ){
                        rec=new String(buf,0,c);
                        sb.append(rec);
                   };c is the number of bytes which were read from the input stream.
    so i save the read bytes into a new string, but only bytes 0-c from the bytearray buf.
    then, i append the whole string to a stringbuffer for later use.

  • DOM: parsing problem, inputstream

    Hi,
    We are developing a simple server that translates a XML query to a SQL query, sends that SQL query to the database, translates the result to a XML resultset and sends it back to the connecting client.
    We are using DOM to interpret the XML in order to build the XML query, since DOM builds a tree (that we use as a buffer), instead of SAX that has to be interpreted realtime.
    Our problem is as follows: the inputstream of the socket act as the input stream for DOM. No exception occures, but at the point when we call domParser.parse();, the thread hangs. When we close the connection, the local output (at the server) is done; the thread continues.
    We assume that the following causes the problem: the inputstream is used to read the XML from. But when the XML is sent over the stream, the stream is not closed. Somehow the parser still expects something. When the clientconnection is closed, the stream is closed and the thread can continue; the parser know that the input is ended.
    Do you know how to solve this? We cannot just close the connection, because we need to receive the result. Does the parser expects some end indicator? For the inputstream for the parser we use a BufferedReader (otherwise we are getting a NullPointerException).
    Thanks! And cheers,
    Jeroen Oosterlaar

    personaly, for doing a similar stuff, on the server I accumulate the XML lines received over the socket, until I bump into a pre-defined stop line, then I send the accumulated XML data to the parser.
    but it might not be the most elegant solution!

  • Problem with inputstreams from socket

    Hi
    This is probably a stupid question, but I really don't know much about server-client programming, and I'm a bit stuck when it comes to helping a friend (who is even more lost than me :p).
    In the code, there is a socket, mySocket. For some reason, there is two objects, one BufferedReader and one ObjectInputStream, both using the same sockets inpustream.
    mySocket = new Socket(servermaskin, PORT);
    in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));     
    out = new PrintWriter(mySocket.getOutputStream(),true);
    clientOutputStream = new ObjectOutputStream(mySocket.getOutputStream());
    clientInputStream = new ObjectInputStream(mySocket.getInputStream());"in" is used to write strings, and clientInputStream to write other objects. I really don't see why not use just the ObjectInputStream to write string as well, since strings are object too. What I am really wondering about is wether having two such object open at the same time, using the same sockets inputstream can be the cause of the problems?
    ~Ulvhild~

    When you create an ObjectOutputStream you have to flush it. Otherwise the header it writes at the start of the stream is not sent for the ObjectInputStream to read.
    clientOutputStream = new ObjectOutputStream(mySocket.getOutputStream());
    clientOutputStream.flush();

  • InputStream partial reading problem

    Hi, I have to read a big file partially, in my function as a parameter i will have
    InputStream - 'is'
    byte[] buffer = new byte[1024];
    long sentBytes = 0;
    int bytesRead = is.read(buffer, 0, 1024);
    while (bytesRead > 0) {
    sentBytes += bytesRead;
    bytesRead = is.read(buffer, 0, 1024);
    counter++;
    i'm reading more than i should- how to cope with that? its a problem with last part of stream i suppose..
    bytesRead = is.read(buffer, 0, chunkSize);
    but when i call buffer.length at the end, it prints lower value than 1024, so where is the problem?

    Hi, I have to read a big file partially, in my
    function as a parameter i will have
    InputStream - 'is'
    byte[] buffer = new
    byte[1024];
    long sentBytes = 0;
    int bytesRead = is.read(buffer, 0, 1024);
    while (bytesRead > 0) {
    sentBytes += bytesRead;
    bytesRead = is.read(buffer, 0,
    1024);
    counter++;
    i'm reading more than i should- how to cope with
    that? its a problem with last part of stream i
    suppose..
    bytesRead =
    is.read(buffer, 0, chunkSize);
    but when i call buffer.length at the end, it prints
    lower value than 1024, so where is the problem?How much are you actually trying to read? It looks like your code will keep reading until the end of the file is reached.

  • A strange problem about InputStream

    I meet a strange problem.
    I have a data file named data.dat whose size is 16k.
    I write a passage of code to read the binary data from data.dat
           byte[] gbData = new byte[8177 * 2];
           // it's length equals to the size of data.dat
           InputStream in = ClassLoader.getSystemResourceAsStream(
               "com/sunway/james/st/res/data.dat");
           in.read(gbData);
           in.close();When I run the program, It's can work well. Then I put all class and resources into a jar file.
    When I run the jar file, I can only get first 600 (and serval more) bytes right. left bytes are 0.
    Who can tell me what happen?

    Thank you.
    I tried to use java.nio to read the data, and there is still the problem.
    flowing is the new codes:
            FileInputStream in =
                new FileInputStream("com/sunway/james/st/res/BIG5.dat");
            ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
            in.getChannel().read(buffer);
            byte[] big5Data = buffer.array();
            in.close();

  • FileUpload problem: InputStream does not contain a serialized object

    Hi All,
    I'm using the FileUpload component in a JSPDynPage and the htmlb component seems to work fine but I cannot read the file (InputStream). I get the following error(IOException): "InputStream does not contain a serialized object".
    Please let me know what is wrong with my code. This is a part of the code I used:
    public FileInputStream sourceFileInput;
    public ObjectInputStream input;
    FileUpload fu;
    fu = (FileUpload) this.getComponentByName("myFileUpload");
    IFileParam fileParam = ((FileUpload) getComponentByName("myFileUpload")).getFile();
    File f       = fileParam.getFile();
    file         = fu.getFile().getFile();
    absolutepath = fu.getFile().getFile().getAbsolutePath();
    this.sourceFileInput = new FileInputStream(file);
    input = new ObjectInputStream(sourceFileInput);
    The last line of code seems to generate te error.

    Hi,
    I have found the answers, thank you both.
    (I included the examle code. Perhaps of some use to someone.)
    FileUpload fu;
    fu = null;
    fu = (FileUpload) this.getComponentByName("myFileUpload");
    //       this is the temporary file
    if (fu != null) {
         IFileParam fileParam = ((FileUpload) getComponentByName("myFileUpload")).getFile();
         if (fileParam != null) {
              // get info about this file and create a FileInputStream
              File f = fileParam.getFile();
              if (f != null) {
                   try {
                        fis = new FileInputStream(f);
                   // process exceptions opening files
                   catch (FileNotFoundException ex) {
                        myBean.setMessage(
                             "1" + f + ex.getLocalizedMessage());
                   isr = new InputStreamReader(fis);
                   br = new BufferedReader(isr);
    String textLine = "";
    do {
         try {
              textLine = (String) br.readLine();
         } catch (IOException e) {
              myBean.setMessage(
                   "1" + e.getLocalizedMessage());
         // Jco append table & put data into the record
         // (I_FILE is the table with txt data that is sent to the RFC)
         I_FILE.appendRow();     
         I_FILE.setValue(textLine, "REC");                              
    } while (textLine != null);

  • Problem While Working with InputStream

    Hi
    I have such code:
            DocumentBuilderFactory factory;
            DocumentBuilder builder;
            Document doc;
                factory = DocumentBuilderFactory.newInstance();
                builder = factory.newDocumentBuilder();
                doc = builder.parse(******); // HERE SHE WANTS InputStreamAs you see in method parse I need to have a variable of type InputStream. And in this InputStream MUST BE DATA!!!
    AND I have an array of strings in memory.
    How can I use THIS ARRAY to input it in method parse

    If you have an array of Strings you can concatenate them and create a ByteArrayInputStream from the newly created String.
    HTH
    Mike

  • Problems with special characters in InputStream or XPath

    Hello everyone,
    I am having problems with special characters such as ", ', - and so on, everything becomes ? (questionmark). (Not with special nordic characthers (å,æ,ø) though.)
    The encoding of the XML is UTF-8, and the server that holds the webservice is setting encoding to UTF-8 also, so no conflict there.
    What I have done is something like this:
    {code}
    String url = "http://www.formula1.com/rss/news/latest.rss"; // This is not the feed I use, it is a custom XML document
    InputSource is = new InputSource(url);
    DocumentBuilderFactory fct = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = fct.newDocumentBuilder();
    Document doc = builder.parse(is);
    Element rootElement = doc.getDocumentElement();
    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    out.print(xPath.evaluate("/rss/channel/title", rootElement)); // The xml is not a RSS feed, this is just an example.
    {code}
    Please let me know what I am doing wrong, or give me a hint of how to solve this in another way.
    Best regards,
    G.Hansen
    Edited by: G.Hansen on Mar 24, 2009 2:39 AM

    Hello, thanks for you reply. I had to rewrite your code a little, and I think that your code would not really compile, if you tried yourself :-)
    I ended up with something like this:
    our environment is running in 1.4 mode, so I could not use the for-each loop :-(
    public String printEntities(String s) {
         char[] sArray = s.toCharArray();
         StringBuffer sb = new StringBuffer();
           for (int i = 0; i < sArray.length; i++) {
             if (sArray[i] > 256)
                  sb.append("&#x" + Integer.toHexString(sArray) + ";");
         } else
              sb.append(sArray[i]);
         return sb.toString();

Maybe you are looking for

  • Edge poster image no longer visible in design mode

    Just updated to Muse 2014.3 In design mode the preview of Edge Animations has been replaced with the "Eg" icon. The animations works just fine but it is more difficult to place them properly without a preview image. I checked the Edge Animation file

  • How to use self-signed Certificate or No-Check-Certificate in Browser ?

    Folks, Hello. I am running Oracle Database 11gR1 with Operaing System Oracle Linux 5. But Enterprise Manager Console cannot display in Browser. I do it in this way: [user@localhost bin]$ ./emctl start dbconsole The command returns the output: https:/

  • BPM with Wok Flow

    hi every body, i am trying to do incorporate Business work flow in the BPM. my scenario is like this........... from sender application, user leave request data will be sent to the BPM , then it has to trigger the Work Flow. here the data will has to

  • RBAC for deploy application to Collections

    Hi, I want an Application admin not be able to deploy application to servers. I think I have to add all my target collection for User and Windows Workstation to the "Security Scope", and then have an security role that can deploy application to colle

  • How can i disable the Enter key in JTextArea?

    How can i disable the Enter key in JTextArea? When i press Enter key in JTextArea,I hope JTextArea do nothing. Thanks!