Java Input Stream

If i have a .txt file in the format:
1 //indicating the number of lines the question is
What is my favorite color?
1. red
2. blue
3.orange
4. yellow
5. green // these 5 are answers
1 //indicating number of lines the question is
How many cars in BMW series?
1. .....
2. .....
3. ..... //answers are always 5 lines
4 ......
5 .......
so each question has exactly 5 answers in the txt file provided.
I want to make my program read the question and 5 lines of answers. Then ask user for answer (get input). And then continue the same pattern throughout the file. I know how to read the whole file but i am having trouble getting it to read question line, 5 answers , get usr_input and do the same thing for rest. Any help?

The program below just reads the whole thing: yes line by line. If i put a do { while lets say (oneLine != null), then it reads the whole thing. But I want it to read the question, then asnwers (5 of them) and ask usr_input.. and continue this pattern. I know i should set up a do while loop for each question.. and that's my main problem.
//the rest of code or the above part which checks for accurate file names and all that works fine. Here is where the problems lies:
String oneLine=null; /* the contents of a line of the user input file */
     try {
     oneLine = fileIn.readLine();
     int store = Integer.parseInt(oneLine);
     catch (IOException e) {
     System.err.println("Sorry, unable to read a line from the file: " + filename);
     System.exit(0);
     System.out.println("Read the line: " + oneLine);

Similar Messages

  • ExecTask - java.io.EOFException: Unexpected end of ZLIB input stream

    BOXI 3.1 FP 7 deployed on AIX environment with all the lang packs. Trying to install SP2 on AIX, when it comes to deploying the war files, AnalyticalReporting, the install encounters error. This error appears to be with size of the war file.  Anyone came across this issue?
    2010-03-30 10:10:00,633   Target - Target "expand_and_package" started.
    2010-03-30 10:10:00,634   Delete - Deleting directory /export/home/Business_Objects/global/deployment/workdir/tomcat55/resources/web/AnalyticalReporting
    2010-03-30 10:10:00,798    Mkdir - Created dir: /export/home/Business_Objects/global/deployment/workdir/tomcat55/resources/web/AnalyticalReporting
    2010-03-30 10:10:00,828    Mkdir - Created dir: /export/home/Business_Objects/global/deployment/workdir/tomcat55/resources/AnalyticalReporting
    2010-03-30 10:19:32,016 *ExecTask - java.io.EOFException: Unexpected end of ZLIB input stream
    2010-03-30 10:19:32,016 ExecTask -      at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java(Compiled Code))
    2010-03-30 10:19:32,017 ExecTask -      at java.util.zip.InflaterInputStream.read(InflaterInputStream.java(Compiled Code))
    2010-03-30 10:19:32,017 ExecTask -      at java.util.zip.ZipInputStream.read(ZipInputStream.java(Compiled Code))
    2010-03-30 10:19:32,017 ExecTask -      at sun.tools.jar.Main.extractFile(Main.java(Compiled Code))
    2010-03-30 10:19:32,017 ExecTask -      at sun.tools.jar.Main.extract(Main.java(Compiled Code))
    2010-03-30 10:19:32,025 ExecTask -      at sun.tools.jar.Main.run(Main.java:228)
    2010-03-30 10:19:32,025 ExecTask -      at sun.tools.jar.Main.main(Main.java:944)
    2010-03-30 10:19:32,051 ExecTask - Result: 1
    2010-03-30 10:19:32,162     Echo - Adding 'webiApplet/**' to the content to bundle with AnalyticalReporting's war file
    2010-03-30 10:19:32,302      Jar - error while reading original manifest: Error opening zip file /export/home/Business_Objects/global/deployment/workdir/tomc
    at55/application/AnalyticalReporting.war
    2010-03-30 10:19:35,354      Jar - Building jar: /export/home/Business_Objects/global/deployment/workdir/tomcat55/application/AnalyticalReporting.war
    2010-03-30 10:20:29,036      Zip - Building zip: /export/home/Business_Objects/global/deployment/workdir/tomcat55/resources/AnalyticalReporting.zip
    2010-03-30 10:23:58,561    Mkdir - Created dir: /export/home/Business_Objects/global/deployment/workdir/tomcat55/resources/web/AnalyticalReporting/WEB-INF
    2010-03-30 10:23:58,564     Copy - Copying 1 file to /export/home/Business_Objects/global/deployment/workdir/tomcat55/resources/web/AnalyticalReporting/WEB-I
    NF
    2010-03-30 10:23:58,597   Delete - Deleting directory /export/home/Business_Objects/global/deployment/workdir/tomcat55/resources/AnalyticalReporting
    2010-03-30 10:35:00,636   Target - Target "expand_and_package" finished.

    Hi,
    Don't know which of this factors solved the problem:
    1. Error server:
    AIX 5.2
    jdk 1.3.17 (minimum from docu: 1.3.11)
    $ORACLE_HOME wasn't in the begining of $PATH
    2. success server:
    AIX 5.3
    jdk 1.4.02
    $ORACLE_HOME is now in the begining of $PATH
    cheers Lao De

  • Java.io.EOFException: Unexpected end of ZLIB input stream

    Hi,
    I am reading .gz file in servlet and writing it in output stream. It works fine for smaller files. For larger file when I reading file and writing output I am getting exceptions as below in order.
    8/6/09 9:52:28:953 CDT] 00000029 ServletWrappe E SRVE0068E: Could not invoke the service() method on servlet /WEB-INF/pages/TilesTemplate/layouttemplate.jsp. Exception thrown : java.lang.IllegalStateException: SRVE0199E: OutputStream already obtained
         at com.ibm.ws.webcontainer.srt.SRTServletResponse.getWriter(SRTServletResponse.java:489)
         at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:170)
         at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:163)
         at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:227)
    ---- Begin backtrace for Nested Throwables
    java.lang.IllegalStateException: SRVE0199E: OutputStream already obtained
         at com.ibm.ws.webcontainer.srt.SRTServletResponse.getWriter(SRTServletResponse.java:489)
         at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:170)
         at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:163)
    *[8/6/09 9:52:28:625 CDT] 00000029 SystemErr R java.io.EOFException: Unexpected end of ZLIB input stream*
    *[8/6/09 9:52:28:656 CDT] 00000029 SystemErr R      at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:238)*
    *[8/6/09 9:52:28:656 CDT] 00000029 SystemErr R      at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:157)*
    *[8/6/09 9:52:28:656 CDT] 00000029 SystemErr R      at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:109)*
    *[8/6/09 9:52:28:656 CDT] 00000029 SystemErr R      at java.io.FilterInputStream.read(FilterInputStream.java:110)*
    *[8/6/09 9:52:28:656 CDT] 00000029 SystemErr R      at sun.nio.cs.StreamDecoder$ConverterSD.implRead(StreamDecoder.java:325)*
    *[8/6/09 9:52:28:656 CDT] 00000029 SystemErr R      at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:223)*
    *[8/6/09 9:52:28:656 CDT] 00000029 SystemErr R      at java.io.InputStreamReader.read(InputStreamReader.java:208)*
    *[8/6/09 9:52:28:656 CDT] 00000029 SystemErr R      at java.io.BufferedReader.fill(BufferedReader.java:153)*
    *[8/6/09 9:52:28:656 CDT] 00000029 SystemErr R      at java.io.BufferedReader.readLine(BufferedReader.java:316)*
    *[8/6/09 9:52:28:656 CDT] 00000029 SystemErr R      at java.io.BufferedReader.readLine(BufferedReader.java:379)*
    *[8/*

    My suggestion would be to run your code as a plain old Java application. Why use a servlet environment to test the problem? There's just too many things going on. So first see if it works the same way in a Java application. If it does, or if it doesn't, you then know where to go next.

  • Oracle Blob using Java help (Error: JVM_recv in socket input stream read )

    I am trying to insert a record with Blob column (size of image 'mg.jpg' about 15KB) and I get the runtime error:
    [java] java.sql.SQLException: Io exception: Connection reset by peer: JVM_recv in socket input stream read
    [java]      at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
    [java]      at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
    [java]      at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:333)
    [java]      at oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2061)
    [java]      at oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:1940)
    [java]      at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2709)
    [java]      at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:589)
    [java]      at test.ProvisioningParser.TestBlob.main(Unknown Source)
    This is what code looks like: I am not sure what's wrong, any help appreciated. Thanks!
         try{
                   Class.forName("oracle.jdbc.driver.OracleDriver");
                   con = DriverManager.getConnection("jdbc:oracle:thin:@VALUED-20606295:1521:dbbook","jvending","jvending");
                   java.util.zip.ZipInputStream zip = new java.util.zip.ZipInputStream(new java.io.FileInputStream(new java.io.File("D:\\work\\mywork\\source\\test\\ProvisioningParser\\test.par"))) ;
                   int len = 0 ;
                   java.util.zip.ZipEntry entry = null;
                   do{
                        entry = zip.getNextEntry();
                        if (entry != null){
                             if (entry.getName().equalsIgnoreCase("mg.jpg")){
                                  len = (int)entry.getSize();
                                  break;
                   }while(entry!=null) ;
                   stmt = con.prepareStatement( "Insert into icon (parid, clientbundleid, id, iconfile ) values ( ?,?,?,?)"
                         stmt.setString(1,"101");
                         stmt.setString(2,"101");
                         stmt.setInt(3,1);                    
                         stmt.setBinaryStream( 4, zip, len);
                   stmt.setQueryTimeout(0);
                   stmt.executeUpdate();
                   con.close();               
              catch(Exception e){
                   e.printStackTrace();
              }Thanks,
    Rashmi

    As a guess what you are doing with that zip stuff is very odd.
    You do realize that it is just going to put some binary data into the blob right? And the methods that is going to use will not necessarily create a 'complete' zip file?
    If you want a zip file then just load the file, dont use the zip classes.
    And if you want part of a zip file, (and want to store the parts as a zip) then extract it from the file and create another zip entity using a byte stream rather than a file.
    Finally I suspect your error with the blob occurs because you do not close the statement. But at any rate you should figure out how to do the blob code independent of the zip stuff.
    And what oracle driver version are you using? Some of the older ones need oracle specific handling for blobs.

  • Java.lang.Process input stream waiting until process is complete to print

    I have tried to simplify this problem as much as possible. Basically, I have a java.lang.Process which executes a simple C program.
    test.c
    #include <stdio.h>
    #include <unistd.h>
    int main()
      printf("foo\n");
      sleep(2);
      printf("bar\n");
    ...The process has an input stream and error stream handler each on a separate thread. I have tried both buffered and unbuffered (BufferedReader, BufferedInputStream, InputStreamReader...) stream handlers. Both produce the same problem of waiting until the process has exited to receive anything from the process's streams.
    The only time this does not happen is when I call fflush(stdout); after each printf(). This can't be a solution because the real application calls a massive C application which would require thousands of fflush()'s to be added. What is causing this to happen? This doesn't happen when the C program is executed from the shell. Is there a way the InputStream can be forced to extract from the stream?

    hi.....
    I have closed the output stream of the process as you told me to do...
    The hitch is that, if my program contains only printf() statements,it works fine
    as soon as scanf() statement is encountered within the C code,it is totally neglected,and the output comes as if no scanf() statement existed in the C code.
    Consequently the thread doesnt wait for input which was bound for scanf() from the thread
    the code...
        public void run()
         try
             PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
             BufferedReader in = new BufferedReader(
                            new InputStreamReader(
                            socket.getInputStream()));
             try
                     Process p;
              p=new ProcessBuilder("./a.out").start();
                     PrintWriter exOut=null;
                     BufferedReader exIn=null;
              exOut = new PrintWriter(p.getOutputStream(),true);
              exIn = new BufferedReader(
                           new InputStreamReader(
                           p.getInputStream()));
                  //String inputLine="", outputLine="";        
                  String str="";
                     int c;          
                  while(true)                   
                        //System.out.println("In While");
                  str="";exOut.close();                  
                        while((c=exIn.read())!=-1)
                                 str=str+(char)(c);
                                    System.out.print(str);
                        str=str+(char)(0);
                        System.out.print(str+"outside");
                        out.print(str);
                        sleep(100);
                        try
                            int x=p.exitValue();
                              out.print(str);
                   System.out.print("Bye 1");
                            String str1="Bye"+(char)(0);
                   out.println(str1);              
                   break;
                        catch(IllegalThreadStateException e)
                            //System.out.println("The Process has not ended yet");
                        //str=str+((char)-1);
                        //System.out.print(str+"Control reaches here too");
                        str="";
                        exOut = new PrintWriter(p.getOutputStream(),true);//I have tried to run the program without this also but the effect is the same
                        while((c=in.read())!=-1)
                            str=str+(char)(c);                                    
                        if(str.contentEquals(""))
                                System.out.print("Bye 2");
                                String str1="Bye"+(char)(0);
                                out.println(str1); 
                                p.destroy();
                                exOut.close();
                                exIn.close();
                                out.close();
                                in.close();        
                                socket.close();
                                break;
                        //str=str+(char)(0);
                  exOut.print(str);
                        try
                            int x=p.exitValue();
                            System.out.print("Bye 3");
                            String str1="Bye"+(char)(0);
                   out.println(str1);
                            break;
                        catch(IllegalThreadStateException e)
                            //System.out.println("The Process has not ended yet");
                  /*while ((inputLine = in.readLine()) != null)
                        exOut.println(inputLine);
                        outputLine=exIn.readLine();
                        //outputLine=inputLine;
                        //out.println(outputLine);}*/                   
             exOut.close();
             exIn.close();
             catch(IOException e)
                  System.err.println("Accept failed."+e);
             out.close();
             in.close();        
             socket.close();
         catch (Exception e)
             e.printStackTrace();
    }

  • Java Input and Output streams

    I have maybe simple question, but I can`t really understand how to figure out this problem.
    I have 2 applications(one on mobile phone J2ME, one on computer J2SE). They commuinicate with Input and Output Streams. Everything is ok, but all communication is in sequence, for example,
    from mobile phone:
    out.writeUTF("GETIMAGE")
    getImage();
    form computer:
    reply = in.readUTF();
    if(reply.equals("GETIMAGE")) sendimage()
    But I need to include one simple thing in my applications - when phone rings there is function in MIDlet - pauseApp() and i need to send some signal to Computer when it happens. But how can i catch this signal in J2SE, because mayble phone rings when computer is sending byte array? and then suddnely it receives command "RINGING"....?
    Please explain how to correcly solve such problem?
    Thanks,
    Ervins

    Eh?
    TCP/IP is not a multiplexed protocol. And why would you need threads or polling to decipher a record-oriented input stream?
    Just send your images in packets with a type byte (1=command, 2=image, &c) and a packet length word. At the receiver:
    int type = dataInputStream.read();
    int length = dataInputStream.readInt();
    byte[] buffer = new byte[length];
    int count, read = 0;
    while ((count = dataInputStream.read(buffer,count,buffer.length)) > 0)
    read += count;
    // At this point we either have:
    // type == -1 || count = -1 => EOF
    // or count > 0, type >= 0, and buffer contains the entire packet.
    switch (type)
    case -1:
    // EOF, not shown
    break;
    case COMMAND: // assuming a manifest constant somewhere
    // process incoming command
    break;
    case IMAGE:
    // process or continue to process incoming image
    break;
    }No threads, no polling, and nuthin' up my sleeve.
    Modulo bugs.

  • How do I return an input stream from a text file

    Suppose there's a class with methods..
    one of the methods is something like..
    public int value() and has a return statement at the end obviously for returning an int value..
    Another method reads a text file and creates an input stream..
    Scanner data  = new Scanner(new File(input.next()));
    I want to return the data when I do a call to this method, but I'm not sure what the method heading would look like..

    flounder wrote:
    Are we supposed to magically know what those errors are? Do you think that copying and pasting the exact error messages and indicating the lines they occur on would be useful to us?Sorry about that..
    I've replicated the same code below; and put the number of the line where the error is.
    +cannot find symbol variable read     [line 21]+
    +cannot find symbol variable read     [line 23]+
    +cannot find symbol variable read     [line 29]+
    +cannot find symbol variable read     [line 31]+
    +cannot find symbol variable inputStream     [line 44]+
    +calculate() in textInput cannot be applied to (java.util.Scanner)     [line 57]+
    the reason I have the _______ for the createInputStream() method is because I'm not really sure what the heading type should be to return the input stream.
    import java.io.*;
    import java.util.*;
    public class textInput
              public void requestFileName()
                   Scanner input = new Scanner(System.in);
                   System.out.print("Enter file name: ");
              public _______ createInputStream() throws FileNotFoundException
                   Scanner input = new Scanner(System.in);
                   Scanner read = new Scanner(new File(input.next()));
                   return read;
              public void calculate() throws IOException
    21           double max;
                   double min;
    23            int count = 0;
                   double total = 0;
                   if (read.hasNextDouble())
                        double temp = read.nextDouble();
    29                 max = temp;
                        min = temp;
    31                 count++
                        total += temp;
                        while (read.hasNextDouble())
                             double current = read.nextDouble();
                             count++;
                             min = Math.min(current, min);
                             max = Math.max(current, max);
                             total += current;
                   System.out.println("Max of: " + max);
                   System.out.println("Min of: " + min);
    44            System.out.println("Average of " + total/count);
              public void close() throws IOException
                   inputStream.close();
              public static void main(String[] args)
                   textInput run = new textInput();
                   try
    57                 run.requestFileName();
                        run.createInputStream();
                        run.calculate();
                        run.close();
                   catch(FileNotFoundException e)
                        System.out.println("File not found.");
                        System.exit(0);
                   catch(IOException e)
                        System.out.prinln("File not found.");
                        System.exit(0);
    }

  • When using URLConnection read input stream error

    hi,
    In my applet I build a URLConnection, it connect a jsp file. In my jsp file I refer to a javaBean. I send two objects of request and response in jsp to javaBean. In javabean return output stream to URLConnect. At that time a error happened.WHY???(Applet-JSP-JAVABean)
    Thanks.
    My main code:
    APPLET:(TestApplet)
    URL url = new URL("http://210.0.8.120/jsp/test.jsp";
    URLConnection con;
    con = url .openConnection();
    con = servlet.openConnection();
    con.setDoInput( true );
    con.setDoOutput( true );
    con.setUseCaches( false );
    con.setRequestProperty( "Content-Type","text/plain" );
    con.setAllowUserInteraction(false);
    ObjectOutputStream out;
    out = new ObjectOutputStream(con.getOutputStream());
    Serializable[] data ={"test"};
    out.writeObject( data );
    out.flush();
    out.close();
    //until here are all rigth
    ObjectInputStream in = new ObjectInputStream( con.getInputStream() );//happened error
    JSP:
    TestBean testBean = new TestBean ();
    testBean .execute(request, response);
    JAVABEAN:
    public void execute( HttpServletRequest request,
    HttpServletResponse response )
    ObjectInputStream in = new ObjectInputStream( request.getInputStream() );
    String direct = (String) in.readObject();
    System.out.prinltn("direct");
    ObjectOutputStream out = new ObjectOutputStream( response.getOutputStream() );
    SerializableSerializable[] data ={"answer"};
    out.writeObject( data );
    out.flush();
    out.close();
    Error detail:
    java.io.StreamCorruptedException: invalid stream header
         at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:729)
         at java.io.ObjectInputStream.<init>(ObjectInputStream.java:251)
         at TestApplet.postObjects(TestApplet.java:172)

    you have to pay attention to the sequence of opening the streams.
    The following example is: client sends a string to server, and servlet sends a response string back.
    client side:
             URL url = new URL( "http://152.8.113.149:8080/conn/servlet/test" );
             URLConnection conn = url.openConnection();   
             System.out.println( "conn: " + conn );
             conn.setDoOutput( true );
             conn.setDoInput( true );
             conn.setUseCaches( false );
             conn.setDefaultUseCaches (false);
             // send out a string
             OutputStream out = conn.getOutputStream();
             ObjectOutputStream oOut = new ObjectOutputStream( out );
             oOut.writeObject( strSrc ); 
             // receive a string
             InputStream in = conn.getInputStream();     
             ObjectInputStream oIn = new ObjectInputStream( in );
             String strDes = (String)oIn.readObject();server side
             // open output stream
             OutputStream out = res.getOutputStream();  
             ObjectOutputStream oOut = new ObjectOutputStream( out );
             // open input stream and read from client
             InputStream in  = req.getInputStream();
             ObjectInputStream oIn = new ObjectInputStream( in );
             String s = (String)oIn.readObject();
             System.out.println( s );
             // write to client
             oOut.writeObject( s + " back" ); I have the complete example at http://152.8.113.149/samples/app_servlet.html
    don't forget to give me the duke dollars.

  • SocketException during reads - JVM_recv in socket input stream read

    I am getting a SocketException when a Java applet talks to our
    WebLogic 7.0 server. The catch is that it only occurs at one site
    (that has very high T1 utilization, although latency is only ~60 ms)
    Our setup is such that the calls hit an Alteon load balancer, which
    then sends the request out to one of 4 IIS clustered servers, where it
    then is sent to one of 2 WL clustered servers. I figured latency
    would be the cause, but on IIS and on WL, the timeouts are set to
    several hundred seconds, so I am not quite seeing where the connection
    is being reset. To be honest, I really don't know if it is WL that is
    killing the connection, as nothing abnormal shows up in the WL log. I
    have seen similar problems in this group, though, although the stack
    traces never follow the same path mine does. I do have the following
    call stack from the Java plug-in console, though. Any ideas would be
    greatly appreciated.
    java.net.SocketException: Connection reset by peer: JVM_recv in socket
    input stream read
         at java.net.SocketInputStream.socketRead0(Native Method)
         at java.net.SocketInputStream.read(Unknown Source)
         at java.io.BufferedInputStream.fill(Unknown Source)
         at java.io.BufferedInputStream.read1(Unknown Source)
         at java.io.BufferedInputStream.read(Unknown Source)
         at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
         at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
         at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
         at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown
    Source)
         at sun.plugin.net.protocol.http.HttpURLConnection.getInputStream(Unknown
    Source)
         at sun.net.www.protocol.http.HttpURLConnection.getHeaderFields(Unknown
    Source)
         at sun.plugin.net.protocol.http.HttpURLConnection.checkCookieHeader(Unknown
    Source)
         at sun.plugin.net.protocol.http.HttpURLConnection.getInputStream(Unknown
    Source)
         at org.xxxx.abstracts.Controller.sendRequest(Controller.java:39)
         at org.xxxx.data.DataMediator.getDataNode(DataMediator.java:46)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Also, here is my code, although I can't see anything on the client
    side that seems off:
    public Object sendRequest( Object request, URL receiver ) throws
    Exception{
    Object response = null;
    URLConnection con = null;
    ObjectOutputStream out = null;
    ObjectInputStream in = null;
    try {
    con = receiver.openConnection();
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setDefaultUseCaches(false);
    con.setAllowUserInteraction(false);
    out = new ObjectOutputStream(con.getOutputStream());
    out.writeObject(request);
    out.flush();
    out.close();
    in = new ObjectInputStream(con.getInputStream());
    response = in.readObject();
    in.close();
    } catch (ClassCastException e) {
    if( out != null ){
    out.close();
    if( in != null ){
    in.close();
    } catch (Exception e) {
    if( out != null ){
    out.close();
    if( in != null ){
    in.close();
    throw e;
    return response;

    There is a known bug on earlier 1.3.1 releases with sockets on Windows 2k
    and XP. I don't remember all the details.
    Peace,
    Cameron Purdy
    Tangosol, Inc.
    http://www.tangosol.com/coherence.jsp
    Tangosol Coherence: Clustered Replicated Cache for Weblogic
    "Keith Patrick" <[email protected]> wrote in message
    news:[email protected]...
    I'm getting the exception on the client, which is an XP machine, while
    the server is Win2K. I can't recall which, but either the applet or
    the server runs 1.3x while the other runs 1.4. I discounted that
    factor, though, as the problem only occurs on one site, which on all
    others it works fine.
    "Cameron Purdy" <[email protected]> wrote in message
    news:<[email protected]>...
    Exception is in the applet or on the server?
    Would one of those by any chance be running on W2K with JDK 131_01 orolder?
    >>
    Peace,
    Cameron Purdy
    Tangosol, Inc.
    http://www.tangosol.com/coherence.jsp
    Tangosol Coherence: Clustered Replicated Cache for Weblogic
    "Keith Patrick" <[email protected]> wrote in message
    news:[email protected]...
    I am getting a SocketException when a Java applet talks to our
    WebLogic 7.0 server. The catch is that it only occurs at one site
    (that has very high T1 utilization, although latency is only ~60 ms)
    Our setup is such that the calls hit an Alteon load balancer, which
    then sends the request out to one of 4 IIS clustered servers, where it
    then is sent to one of 2 WL clustered servers. I figured latency
    would be the cause, but on IIS and on WL, the timeouts are set to
    several hundred seconds, so I am not quite seeing where the connection
    is being reset. To be honest, I really don't know if it is WL that is
    killing the connection, as nothing abnormal shows up in the WL log. I
    have seen similar problems in this group, though, although the stack
    traces never follow the same path mine does. I do have the following
    call stack from the Java plug-in console, though. Any ideas would be
    greatly appreciated.
    java.net.SocketException: Connection reset by peer: JVM_recv in socket
    input stream read
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.io.BufferedInputStream.fill(Unknown Source)
    at java.io.BufferedInputStream.read1(Unknown Source)
    at java.io.BufferedInputStream.read(Unknown Source)
    at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
    at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
    at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown
    Source)
    at
    sun.plugin.net.protocol.http.HttpURLConnection.getInputStream(Unknown
    Source)
    at sun.net.www.protocol.http.HttpURLConnection.getHeaderFields(Unknown
    Source)
    atsun.plugin.net.protocol.http.HttpURLConnection.checkCookieHeader(Unknown
    Source)
    atsun.plugin.net.protocol.http.HttpURLConnection.getInputStream(Unknown
    Source)
    at org.xxxx.abstracts.Controller.sendRequest(Controller.java:39)
    at org.xxxx.data.DataMediator.getDataNode(DataMediator.java:46)
    at sun.applet.AppletPanel.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    Also, here is my code, although I can't see anything on the client
    side that seems off:
    public Object sendRequest( Object request, URL receiver ) throws
    Exception{
    Object response = null;
    URLConnection con = null;
    ObjectOutputStream out = null;
    ObjectInputStream in = null;
    try {
    con = receiver.openConnection();
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setDefaultUseCaches(false);
    con.setAllowUserInteraction(false);
    out = new ObjectOutputStream(con.getOutputStream());
    out.writeObject(request);
    out.flush();
    out.close();
    in = new ObjectInputStream(con.getInputStream());
    response = in.readObject();
    in.close();
    } catch (ClassCastException e) {
    if( out != null ){
    out.close();
    if( in != null ){
    in.close();
    } catch (Exception e) {
    if( out != null ){
    out.close();
    if( in != null ){
    in.close();
    throw e;
    return response;

  • Sending Control-Z to Input Stream

    Hi everyone,
    I'm writing an interface to a command line program, and
    one of it's features is that it will accept "forms" through
    standard input. The default is that notepad will open
    when the command is typed, and you can edit the form
    through there.
    To accept the form through standard input, you have to
    send it the form, and then tell it the form is complete.
    This is done using the CTRL-Z keypress, at least when
    typing the form in with the keyboard.
    I need to do this with Java.
    There is another post which poses the same question at
    http://forum.java.sun.com/thread.jsp?forum=1&thread=3050
    so I attempted that solution.. and that didn't work.
    I had the system print out the form as it was being written,
    and the form displayed properly, followed by what was
    supposed to be a CTRL-Z character, which appeared
    on screen (DOS Window) as an arrow pointing right.
    Here is the code constructing the form and adding what i've been told is "ctrl-z":
    new StringBuffer(form+System.getProperty("line.separator")).append(CTRL_Z).append(System.getProperty("line.separator")))CTRL_Z is defined as:
    public static final char CTRL_Z = 26;Does anyone have any other suggestions that might be able to help me?
    If you need more information/code provided, I can do so.
    Thanks for any help!
    Kefka.

    You can't actually send anything to an input stream. But let's suppose you have an output stream somewhere that is connected to the standard input of this command line program. Try sending a byte, not a character, that contains 26 to it (yes, ctrl-z is indeed 26). This has a better chance of working than the character idea, because Java is going to translate your character-26 from Unicode to bytes using your system's default encoding. And I can't predict what that might end up as. But it will leave the byte 26 alone and just send it... I hope. Can't guarantee this.

  • How to get input stream of other application

    Using Java is their any way to get the input stream of another applicaton?. For example i will start a java program and minimize it. Then i will start a notepad and type some thing in it. Java program should print all matters i am typed in notepad.
    Is it possible using java?
    Thanks in advance

    You have many ways to do that in C++. Read about Hooks and you will understand how u can do that. Anyway, even without hooks, u can get the messages from other applications in C++. So, let C++ get the data from other applications for you and let ur java program get data from the C++ program.

  • Parse XML input stream (no .xml file)?

    i have a java applet calling a web service that returns XML data as an input stream (char by char from SOAP) to this applet. if i append a all the chars to a string, is there some XML tool that will parse the string as if it were an XML document (like a getElement functions)?
    the applet cannot write the data to a .xml file, and i don't want to mess around with .jarsigning. any ideas?
    thanks,
    jonathan

    The XML parsers you are likely to be using support receiving input from a variety of sources besides files. For example you could parse XML from a String variable by passing a StringReader wrapping that String to the parser. Check the documentation for more details.

  • JDBC Connection reset by peer: JVM_recv in socket input stream read

    Hey Guys,
    Has anyone seen this issue? We get this error in our Weblogic app logs at times and no one is able to login to our application. Our database server and SQL server seem fine at a high level. Any ideas what is causing this?
    com.s1.arch.persistence.exception.PersistenceException weblogic.jdbc.mssqlserver4.TdsException: I/O exception while talking to the server, java.net.SocketException: Connection reset by peer: JVM_recv in socket input stream read
    Thanks

    please make sure that there is no Firewall between your servers and DB server. this message usually happen when there is a fire wall between the servers. if yes please make sure that the connection time on fire wall is longer than the time needed to complete an operation another thing that you need to check if you have a fire wall which is to make sure that Oracle DBMS return the request to the same port that it is listening to (1521 default).

  • Playing input stream audio in j2me

    want to make a text-to-speech synthesizer for mobile phones.
    for that i am using FreeTTS (text-to-speech synthesizer written in java)
    so i have made a client-server model where i have a midp client which is sending text to the FreeTTS acting as a server.... for this i am using socket...
    so basically -- client is sending text to server -- server processes the text and sends the audio stream back to client
    the problem is i dont know how to play the audio stream received on client side
    i tried to copy it in a buffer but its not working..
    do i need to save the file in some format before playing it?
    or can the player play the audio stream directly?
    this is how i am copying the contents in the buffer
    try
    InputStream is = socketConnection.openInputStream();
    byte[] buff = new byte[1024];
    int bytesIn = is.read(buff, 0, 1024);
    ByteArrayInputStream bis = new ByteArrayInputStream(buff);
    player = Manager.createPlayer(bis, "audio/x-wav" );
    player.start();
    but it gives an error saying
    javax.microedition.media.MediaException: Malformed wave media
    i tried to display the contents of bis on console it reads
    java.io.ByteArrayInputStream@d590dbc
    i tried the same with the Free TTS client and got the same output.
    so i think client socket is even receiving the audio stream properly...however, im not sure.
    is the whole client-server using socket idea correct?
    if yes, please tell me how to play this audio stream in j2me (the client)
    if it is wrong then please tell me a correct way to do this.
    can the input stream be stored as a WAV file and then played? if yes, then how can i store it as a WAV file? Can this be achieved by appending a WAV header?

    I once tried the similar thing, I ended up buffer all the content locally (from bluetooth), then play the wave file.
    Maybe someone else has better idea.

  • JVM_recv in socket input stream error

    I've opened a socket and I'm able to access the OutputStream. However, when I try to wrap a ObjectInputStream around the socket's InputStream, I get this error:
    SocketException: Connection reset by peer: JVM_recv in socket input stream read.
    What should I be looking for?
    Larry

    Here's the code which appears to be relevant, with some commentary on what happens when it is run. Large portions of (hopefully) irrelevant code have been snipped.
    Client:
    COMMENT: Start a server using RMI. This appears to
    COMMENT: succeed, since a message printed by this
    COMMENT: server does appear.
    try {
    DistLrnRemoteData dlrd =
    (DistLrnRemoteData)Naming.lookup(
    "//"+personHost+
    "/DistanceLearningData");
    dlrd.activatePersonServer(); // Get server going
    catch (Exception e) {
    System.err.println(e);
    COMMENT: This line is NOT printed, so apparently
    COMMENT: there is no Exception.
    System.err.println("Unable to initialize remote Person server");
    e.printStackTrace(System.err);
    Person result = new Person();
    int count = 10;
    boolean opened = false;
    Socket gpsocket = null;
    while (!opened) {
    try {
    COMMENT: The client attempts to open the socket
    COMMENT: here. The server never seems to accept it,
    COMMENT: but this call appears to succeed. There is
    COMMENT: no Exception. The server is running code
    COMMENT: from the class RemoteDataServer, so the
    COMMENT: port should be the same. The testing was
    COMMENT: done with a single host acting as both
    COMMENT: client and server, so there isn't any firewall
    COMMENT: or network outage problem.
    gpsocket = new Socket(personHost,
    RemoteDataServer.personReadPort);
    opened = true;
    catch (IOException ioe) {
    count--;
    if (count <= 0) {
    COMMENT: This line is NOT printed, so apparently there
    COMMENT: is no IOException when the Socket is
    COMMENT: created. Nor does an UnknownHostException
    COMMENT: or SecurityException stop the program.
    System.err.println(ioe);
    ioe.printStackTrace(System.err);
    result = null;
    return result;
    try {
    Thread.sleep(1000);
    catch (InterruptedException ie) {
    System.err.println(ie);
    ie.printStackTrace(System.err);
    // Read the serialized object
    try {
    COMMENT: No problem with the next line, which attempts
    COMMENT: to access the OutputStream of the socket.
    MyStringWriter msw = new MyStringWriter(
    gpsocket.getOutputStream());
    COMMENT: The next line causes the message.
    ObjectInputStream ois =
    new ObjectInputStream(gpsocket.getInputStream());
    msw.write(personRealName);
    // Now read the resulting Person.
    try {
    result = (Person)(ois.readObject());
    catch (ClassNotFoundException cnfe) {
    System.err.println(cnfe);
    cnfe.printStackTrace(System.err);
    System.exit(4);
    catch (IOException ioe) {
    System.err.println(ioe);
    ioe.printStackTrace(System.err);
    result = null;
    Server:
    public void activateFocusServer() throws java.rmi.RemoteException {
    String [] cmd = new String[2];
    cmd[0] = new String("java");
    cmd[1] = new String("RemoteDataServer");
    try {
    COMMENT: FORTE's Output window shows a message
    COMMENT: from this process
    Process dbserver =
    Runtime.getRuntime().exec(cmd); // Server will self-destruct
    // after a timeout period
    catch (IOException ioe) {
    COMMENT: This message is never printed
    System.err.println(ioe);
    ioe.printStackTrace(System.err);
    RemoteDataServer:
    public RemoteDataServer() {
    try {
    ...many different servers started here...
    ServerSocket PersonReadSocket = new ServerSocket(personReadPort);
    PersonReadListener prl = new PersonReadListener(PersonReadSocket);
    prl.start();
    catch (IOException ioe) {
    COMMENT: This message is never printed.
    System.err.println(ioe);
    ioe.printStackTrace(System.err);
    COMMENT: PersonReadListener is an inner class:
    class PersonReadListener extends java.lang.Thread {
    private Thread BaseThread;
    private ServerSocket theSocket;
    /** Creates an object to listen for PersonRead requests
    * @param ss The server socket to listen with
    public PersonReadListener(ServerSocket ss) {
    theSocket = ss;
    /** Initializes the thread to listen for PersonRead requests
    public void start() {
    BaseThread = new Thread(this);
    BaseThread.start();
    /** The code for the server to listen for PersonRead requests
    public void run() {
    while(true) {
    try {
    COMMENT: This code doesn't have access to System.err
    COMMENT: so a file is created to print debugging output
    PrintWriter debug = new PrintWriter(new FileWriter("person.debug"));
    COMMENT: The next line IS printed, so the server gets
    COMMENT: this far.
    debug.println("Waiting for connection for person's name");
    debug.close();
    PersonReadClientConnection someone =
    new PersonReadClientConnection(theSocket.accept());
    COMMENT: If the previous "debug.close" line is
    COMMENT: commented out and the next two lines are
    COMMENT: uncommented, the next line is NOT
    COMMENT: printed, so apparently the accept nevers
    COMMENT: happens! Why does the accept fail, but
    COMMENT: the client's socket creation succeed?
    // debug.println("Accepted a connection");
    // debug.close();
    someone.start();
    catch (IOException ioe) {
    COMMENT: These lines are NOT printed
    System.err.println(ioe);
    ioe.printStackTrace(System.err);

Maybe you are looking for

  • IMac 700 mhz dv. 60gb hard dirve 58 free Set up trouble, new to me

    This is a new computer to me but part of the last owners names remain on the home icon. Having difficulty with crashing when running classic 9.2.1 and 10.1 updated 10.1.5. I have upgraded the firmware to 4.1.9 as well.The apple hardwaredisk pointed t

  • Is there any form of system cleanup  for mac air

    is there any form of system cleanup for mac air

  • Calculation Script-Prob

    Hi all, MtoT/Msales/MMKTG accocunts members there is no members formulas.But Shared members is there .is there any problem? SET MSG Summary; SET CACHE HIGH; SET UPDATECALC OFF; SET CALCPARALLEL 3; /*Clear Section PLRTNYR Final Version Oct to Dec*/ FI

  • Index third level entry issue

    I have a word document with Index marking. The index marking has three levels. When we import the word document into InDesign CS5 or later it shows up correctly without any mistake. However, when we export the content as RTF format the third level en

  • ICal won't open after downgrade.

    I had updated to 10.5 this year (because of new software). Meanwhile my iMac (G5) has gone to a repair service, and I was given a G4 as a loan until my iMac is fixed (if this ever happens). Because I couldn't run my new CS4 software on the G4, I had