Odd behaviour appending to System.out PrintStream

I've run into some unexpected behaviour with the System.out PrintStream object. When I append characters to it I'm expecting the characters to be displayed on screen much like I'd expect the characters to be written to a file using a FileOutputStream. What seems to happen is that the characters are written to the PrintStream but the process continues on and on adding some unseen character (newline?). The following code generates the behaviour I"m talking about. The main method is a bit contrived but does the job. You'll likely have to increase your heap size to run this (-Xmx512m worked for me):
{code}
package output.stream.problem;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Random;
* A class used to introduce transition/transversion errors into DNA sequences. Error types are introduced
* with equal probability and are mutually exclusive.
* @author twb
public class GenomicDNAMutator {
     private HashMap<Integer,Character> mutations=new HashMap<Integer,Character>();
     private Reader sequenceSource;
     private Random rand=new Random();
     private double errorRate=-1;
     public GenomicDNAMutator(String fileName, double errorProbability) {
          try {
               sequenceSource=new FileReader(fileName);
               errorRate=errorProbability;
          } catch (FileNotFoundException fnfe) {
               System.err.println("Could not open file "+fileName);
               fnfe.printStackTrace();
     public GenomicDNAMutator(File file, double errorProbability) {
          try {
               sequenceSource=new FileReader(file);
               errorRate=errorProbability;
          } catch (FileNotFoundException fnfe) {
               System.err.println("Could not open file "+file);
               fnfe.printStackTrace();
     public GenomicDNAMutator(Reader is, double errorProbability) {
          sequenceSource=is;
          errorRate=errorProbability;
     public void process() {
          this.process(System.out);
     public void process(OutputStream os) {
          BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
          BufferedReader br=new BufferedReader(this.sequenceSource);
          char nucleotide;
          char[] a=new char[]{'T','C','G'};
          char[] t=new char[]{'A','C','G'};
          char[] c=new char[]{'A','T','G'};
          char[] g=new char[]{'A','T','C'};
          char[][] errorMatrix=new char[][]{a,t,c,g};
          int matrixIndex=-1;
          try {
               int count=0;
               int i=0;
               while((i=br.read())!=-1) {
                    nucleotide=(char)i;
                    count++;
                    double d=rand.nextDouble();
                    if(d<=this.errorRate) {
                         switch(nucleotide) {
                         case 'A':
                              matrixIndex=0;
                              break;
                         case 'T':
                              matrixIndex=1;
                              break;
                         case 'C':
                              matrixIndex=2;
                              break;
                         case 'G':
                              matrixIndex=3;
                              break;
                         int pos=rand.nextInt(3);
                         this.mutations.put(count,nucleotide);
                         nucleotide=errorMatrix[matrixIndex][pos];
                    bw.append(nucleotide);
               bw.flush();
               bw.close();
          } catch (IOException ioe) {
               System.err.println("Could not read the input source");
     public Reader getIn() {
          return sequenceSource;
     public void setSequenceSource(Reader in) {
          this.sequenceSource = in;
     public static void main(String[] args) throws Exception {
          StringBuilder sb=new StringBuilder();
          for(int i=0;i<30000000;i++) {
               sb.append('A');
          System.out.println("Mock sequence built");
          GenomicDNAMutator gdm=new GenomicDNAMutator(new StringReader(sb.toString()),1d/100d);
          * Run the program using one of the process statements
          gdm.process(new FileOutputStream(new File("c:/text.txt")));
//This one uses the System.out PrintStream object
//          gdm.process();
          System.out.println("done");
{code}
I see this behaviour with java 1.6.0_10-beta and java 1.5.0_11
Thanks for any insight you can give to this.
- Travis

twb wrote:
I've run into some unexpected behaviour with the System.out PrintStream object. When I append characters to it I'm expecting the characters to be displayed on screen much like I'd expect the characters to be written to a file using a FileOutputStream. What seems to happen is that the characters are written to the PrintStream but the process continues on and on adding some unseen character (newline?). The following code generates the behaviour I"m talking about. The main method is a bit contrived but does the job. You'll likely have to increase your heap size to run this (-Xmx512m worked for me):Yes, this is the case. If you look at the javadoc for PrintStream it talks about the "auto-flush on newline" feature. what is your question?

Similar Messages

  • Why System.out.println not PrintStream.println ?

    Hi, just a beginner question
    I just wonder why should we use System.out.println, not PrintStream.println ?
    the field out in the System class is the instance of PrintStream class, isn't it?
    So why don't we just use the PrintStream class directly?
    Thanks..
    Edited by: riff_almighty on Oct 27, 2007 3:27 AM

    According to the api:
    A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Two other features are provided as well. Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the checkError method. Optionally, a PrintStream can be created so as to flush automatically; this means that the flush method is automatically invoked after a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written.
    So there is nowhere mentioned about the PrintStream associated with the user console. System.out is the one instance of PrintStream which is associated with the console...
    Also println() is not a static method and cant be called upon the class...
    Edited by: VijayBabu on Oct 27, 2007 12:51 AM

  • Parse RSS feed -System.out

    Hi,
    As below i have been reading RSS feeds.
    When i execute the parser.parse(url) method i get a dump of the xml bones from the feed onto System.out, which in my case is a catalina log file.
    Is there any way/method that im not aware of that can prevent this going to System.out?
    public void readRSSDocument() throws Exception {
            //Create the parser
            RssParser parser = RssParserFactory.createDefault();
            //Parse our url
            Rss rss = parser.parse(
                    new URL("http://rss.cnn.com/rss/cnn_world.rss"));
        }output:
    <rss>
    <channel>
    <title>
    </title>
    <link>
    </link>
    <description>
    </description>
    <language>
    </language>
    <copyright>
    </copyright>
    <pubDate>
    </pubDate>
    <ttl>
    </ttl>
    <image>
    <title>
    </title>
    <link>
    </link>
    <url>
    </url>
    <width>
    </width>
    <height>
    </height>
    <description>
    </description>
    </image>
    <atom10:link>
    </atom10:link>
    <atom10:link>
    </atom10:link>
    <item>
    <title>
    </title>
    <guid>
    </guid>
    <link>
    </link>
    <description>
    </description>
    <pubDate>
    </pubDate>
    <feedburner:origLink>
    </feedburner:origLink>
    </item>
    <item>
    <title>
    </title>
    <guid>
    </guid>
    <link>
    </link>
    <description>
    </description>
    <pubDate>
    ..

    I am presuming that you picked up the code from [this tutorial|http://java.sun.com/developer/technicalArticles/javaserverpages/rss_utilities/]
    Looks like the library was compiled with System.out.println() statements in it.
    There is always the handy little method "System.setOut()" to redirect it.
    Alternatively, decompile the code, delete/comment the System.out.println statements and then recompile it.
    Its not that hard. Here's the offending class:
    // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
    // Jad home page: http://www.kpdus.com/jad.html
    // Decompiler options: packimports(3)
    // Source File Name:   DocumentHandler.java
    package com.sun.cnpi.rss.handlers;
    import com.sun.cnpi.rss.elements.Element;
    import com.sun.cnpi.rss.elements.Rss;
    import java.io.PrintStream;
    import java.util.*;
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    // Referenced classes of package com.sun.cnpi.rss.handlers:
    //            NullElementHandler, ElementHandler, HandlerException
    public class DocumentHandler extends DefaultHandler
        public DocumentHandler()
            handlers = new HashMap();
            handlerStack = new Stack();
            parentStack = new Stack();
            rss = new Rss("rss");
            handlers.put(null, new NullElementHandler());
            parentStack.add(rss);
        public void registerHandler(String key, ElementHandler handler)
            handlers.put(key.toLowerCase(), handler);
        public void addToParentStack(Element parent)
            parentStack.add(parent);
        public Element popFromParentStack()
            return (Element)parentStack.pop();
        public Element peekParentStack()
            return (Element)parentStack.peek();
        public void startElement(String uri, String localName, String qName, Attributes attributes)
            throws SAXException
            //System.out.println("<" + qName + ">");
            try
                ElementHandler currentHandler = (ElementHandler)handlers.get(qName.toLowerCase());
                handlerStack.add(currentHandler);
                if(currentHandler != null)
                    Element parent = (Element)parentStack.peek();
                    currentHandler.startElement(this, parent, uri, localName, qName, attributes);
            catch(HandlerException e)
                e.printStackTrace();
            super.startElement(uri, localName, qName, attributes);
        public void characters(char ch[], int start, int length)
            throws SAXException
            StringBuffer buffer = new StringBuffer();
            Element element = (Element)parentStack.peek();
            if(element.getText() != null)
                buffer.append(element.getText());
            buffer.append(ch, start, length);
            element.setText(buffer.toString());
            super.characters(ch, start, length);
        public void endElement(String uri, String localName, String qName)
            throws SAXException
            //System.out.println("</" + qName + ">");
            if(!handlerStack.isEmpty())
                try
                    ElementHandler currentHandler = (ElementHandler)handlerStack.pop();
                    if(currentHandler != null)
                        Element parent = (Element)parentStack.peek();
                        currentHandler.endElement(this, parent, uri, localName, qName);
                catch(HandlerException e)
                    e.printStackTrace();
            super.endElement(uri, localName, qName);
        public Rss getRss()
            return rss;
        private Map handlers;
        private Stack handlerStack;
        private Stack parentStack;
        private Rss rss;
    }

  • Redirect, System.out  ?

    Hi.
    I want to redirect System.out to a Swing Component like JTextArea, etc.
    try with printstream, Reader, etc. but i dont know how.!.
    I want to see, messages (The standard out) in a Swing Component.
    plis some help..
    tnks.

    I was using the Redirect method you made edna for my software and it works wonderfully when using strings, unfortunately I ran in to a strange problem which is fitting since my current objective is very strange.
    I am writing a piece of software that has an embedded jython interpreter in it. When I execute my jython scripts all the output went to the console and I had no direct way of saying append to this particular text area since I wasn't able to pass my Java GUI class in to the script.
    Thus redirecting my output with your method came in quite handy. This is where the problem comes in. I tried the println function in my regular java classes and all the primitive types worked fine, but within in the script only String worked. Here is the code for the println function
    PrintStream stdout = new PrintStream(System.out) {
       public void println(String x) {
          outputTextArea.append(x + "\n");
       public void println(int x) {
          outputTextArea.append(x + "\n");
       public void println(boolean x) {
          outputTextArea.append(x + "\n");
       public void println(Object x) {
          outputTextArea.append(x.toString() + '\n');
    };Here is the sample Jython code:
    import JythonScripter
    System.out.println(4) #fails to print correctly
    System.out.println("HelloWorld") #works
    System.out.println(10) #fails
    System.out.println("Goodbye Cruel World") #works
    If you have any advice on why strings would work but not other types I would greatly appreciate it.

  • Redirecting System.out to a JTextArea

    How can I redirect the System.out Stream into a JTextArea?
    I found the method System.setOut(PrintStream out) but I don't know
    how to get the PrintStream of my TextArea.

    I don't know if this is the most efficient way but it provides an example of using Pipes:
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TextAreaStream extends JTextArea implements Runnable{
         private static final PipedOutputStream _pipeOut = new PipedOutputStream();
         static{
                   System.setOut( new PrintStream(_pipeOut) );
         private InputStream _pipeIn;
    private byte[] buffer = new byte[256];
         public TextAreaStream(){
              this(1,10);
         public TextAreaStream(int numRows, int numCols){
              super(numRows, numCols);
              Thread t = new Thread(this);
              t.setDaemon(true);
              t.start();
              try{
              pipeIn =  new BufferedInputStream(new PipedInputStream(pipeOut));
              catch(IOException e){
                   System.err.println("Error creating pipe: "+e);
         public void run(){
              while(true){
                   try{
                        //blocks at read
                        int bytesRead = _pipeIn.read(buffer);
                        append(new String(buffer,0,bytesRead));
                   catch(IOException e){
                        System.err.println(e);
         public static void main(String[] args){
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JTextArea text = new TextAreaStream();
              text.setBorder(BorderFactory.createTitledBorder("System.out"));
              f.getContentPane().add(text);
              //Add an input component
              JPanel north = new JPanel(new FlowLayout(FlowLayout.LEFT));
              final JTextField field = new JTextField(25);
              north.add(field);
              north.add(new JLabel("Add text, press Enter"));
              f.getContentPane().add(north, BorderLayout.NORTH);
              field.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        System.out.println(field.getText());
                        field.setText("");
    f.setSize(600, 400);
              f.show();
    }

  • Redirecting System.out() output to a JTextArea control

    I want to be able to redirect System.out() and System.err() messages to a JTextArea control:
    I know how to redirect output to a file as follows:
    FileOutputStream fos =
    new FileOutputStream(filename, true);
    PrintStream ps = new PrintStream(fos, true);
    System.setOut(ps);
    System.setErr(ps);
    How can I set it up so that I can recognise when messages have been to System.out() with a view to displaying the message within the JTextArea?
    I guess I need to set it up so that the JTextArea control acts as an Observer. The bit I'm having difficulty with is figuring out how I can automatically determine when information has been written to System.out()?
    Hopefully I'm explaining my issue in enough detail and clarity.
    thanks
    - Garry

    I would suggest you set up a separate thread to monitor System.out. Use a PipedOutputStream and redirect System.out to that, then connect that to a PipedInputStream that your other thread is continually waiting to read. Each time that thread reads a line, it should append the line to the JTextArea, using SwingUtilities.invokeLater.
    This is just a rough outline of something that might work. Hope it helps.

  • Redirecting System.out to a textfield

    I want the output created by System.out (especially error messages) redirected to a textfield in stead of the console. How can I do this?

    this is how I've done it. Just create a new instance of this class and pass in your TextArea. It redirects System.out and checks for messages on System.out every 5 seconds.
    import java.io.*;
    import javax.swing.*;
    public class TextOut
    implements Runnable
         private JTextArea text;
         private Reader in;
         private Thread t;
         public TextOut( JTextArea text )
              throws Exception
              this.text = text;
              PipedOutputStream pout = new PipedOutputStream();
              System.setOut( new PrintStream( pout ) );
              in = new InputStreamReader( new PipedInputStream( pout ) );
              t = new Thread( this );
              t.start();
         public void run()
              while( true )
                   try
                        StringBuffer buffer = null;
                        while( in.ready() )
                             if ( buffer == null ) buffer = new StringBuffer();
                             buffer.append( (char)in.read() );
                        if ( buffer != null )
                             text.append( buffer.toString() );
                             java.awt.Rectangle r = new java.awt.Rectangle();
                             text.computeVisibleRect( r );
                             text.repaint( r );
                        t.sleep( 5000 );
                   } catch (IOException ioe) {
                        text.append( "" + ioe );
                   } catch (InterruptedException ie ) {
                        text.append( "" + ie );

  • Urgent: Redirecting System.out.println to more than one place

    Hi All,
    I want to divert all my System.out.println() statements to a Log file as well as on to the screen.
    But only one of the 2 options actually works.
    So if anyone can suggest me some ways I will appreciate very much.
    My code looks something like this:-
    if (m_filename != null) {
    try {
    FileOutputStream fos = new FileOutputStream(m_filename);
    PrintStream ps = new PrintStream(fos);
    System.setOut(ps);
    System.setErr(ps);
    //This code Added for Printing Onto Screen But it does not work
    Stream ps1 = new PrintStream(System.out);
    System.setOut(ps1);
    System.setErr(ps1);
    } catch (IOException ioe) {
    System.out.println("Could not create log file " + m_filename + " because " + ioe);
    As far as logging onto file is menat it works when i set it but printing onto screen does not.
    How can i achive it
    Thanks
    Raj

    Hi,
    You are right but in my current scenario i cannot incorporate this log4j because my application is using some other framework and I am just trying to override this frameworks loggig behaviour so that it logs to both a log file as well as on to the screen.
    Here is the code that this framework uses for logging and i am simply overriding it to do the reqd thing but its not working for me:-
    * Resets the System's out and err OutputStreams to the Launcher's
    * own ThreadedOutputStream, so that output from different threads
    * can be tracked efficiently.
    protected void setOutputStreams() {
         if (scInfo.size() <= 1) {
    // don't need Threaded handling with one thread
    if (m_filename != null) {
    try {
    FileOutputStream fos = new FileOutputStream(m_filename);
    PrintStream ps = new PrintStream(fos);
    System.setOut(ps);
    System.setErr(ps);
    //Added for Printing Onto Screen
                             PrintStream ps1 = new PrintStream(System.out);
    System.setOut(ps1);
    System.setErr(ps1);
    } catch (IOException ioe) {
    Debug.fatalError("Launcher.setOutputStreams","Could not create log file " + m_filename + " because " + ioe);
    else {
    Debug.information("Launcher.setOutputStreams","Initializing ThreadedPrintStream");
    if (m_filename == null) {
    System.setOut(new ThreadedPrintStream(System.out));
    System.setErr(new ThreadedPrintStream(System.err));
    else {
    PrintStream out = new ThreadedPrintStream(m_filename);
    System.setOut(out);
    System.setErr(out);
    //Added for Printing Onto Screen
    System.setOut(new ThreadedPrintStream(System.out));
    System.setErr(new ThreadedPrintStream(System.err));
    Debug.information("Launcher.setOutputStreams","ThreadedPrintStream initialized.");
    Thanks
    Raj

  • System.out.printIn errors

    ok the book gives me this source code:
    public class Ellsworth {
    public static void main(String[] arguments) {
    String line1 = "The advancement of the arts, from year\n";
    String line2 = "to year, taxes our credulity, and seems\n";
    String line3 = "to presage the arrival of that period\n";
    String line4 = "when human improvement must end.";
    String quote = line1 + line2 + line3 + line4;
    String speaker = "Henry Ellsworth";
    String title = "U.S. Commissioner of Patents";
    String from = "1843 Annual Report of the Patent Office";
    System.out.printIn('\u0022' + quote + '\u0022');
    System.out.printIn("\t" + speaker);
    System.out.printIn("\t" + title);
    System.out.printIn("\t" + from);
    I type that in, and in msdos when I type javac ellsworth.java, it gives me the following:
    ellsworth.java:11: cannot resolve symbol
    symbol : method printIn (java.lang.String)
    location: class java.io.PrintStream
    System.out.printIn('\u0022' + quote + '\u0022');

    ellsworth.java:12: cannot resolve symbol
    symbol : method printIn (java.lang.String)
    location: class java.io.PrintStream
    System.out.printIn("\t" + speaker);

    ellsworth.java:13: cannot resolve symbol
    symbol : method printIn (java.lang.String)
    location: class java.io.PrintStream
    System.out.printIn("\t" + title);

    ellsworth.java:14: cannot resolve symbol
    symbol : method printIn (java.lang.String)
    location: class java.io.PrintStream
    System.out.printIn("\t" + from);

    can anyone solve this for me please? I have SDK 1.3.1_04 (folder called jdk 1.3.1_04) and this is seroiusly pissing me off, I also have windows 2000 built on NT4.0 technology. any way to solve this would be very appreciated :)

    Actual behaviour of 1.4.0_01 in Windows 98se is as follows:
    Case 1
            Class name A
            File name  A.java
            javac A.java    compiles clean
            javac a.java    compiles clean
    Case 2
            Class name a
            File name  a.java
            javac A.java    compiles clean
            javac a.java    compiles clean
    Case 3
            Class name a
            File name  A.java
            javac A.java    compile fails
            javac a.java    compiles clean
    Case 4
            Class name A
            File name  a.java
            javac A.java    compiles clean
            javac a.java    compile fails
    A generalized statement of the behaviour is:.
    If (class name and file name case match) {
        the program will compile with any commandline name case
    If (class name and file name case do not match) {
        if (the commandline name case matches the class name case) {
            the program will compile
        } else {
            the program will fail to compile
    }

  • Capturing System.out messages

    Hey all,
    Just wondering what the easiest way to capture System.out messages of a process, and store these messages in an Array, Vector, or a Buffer where I could read these messages line by line later?
    Basically one process System.out.println()'s information I need to use as a variable for a second process. Any help would be greatly appreciated.
    Thanks!

    Here is a class which redirects standard out and err to a JscrollPane.
    import java.io.*;
    import javax.swing.*;
    public class EOutputConsole extends JScrollPane {
      Object lock = new Object();
      final JTextArea text = new JTextArea(10,30);
      PrintStream consoleOut;
      public EOutputConsole() {
        setViewportView(text);
        setupOutput();
       * An extention of PrintStream that notifies a lock
       * as it's executing its write method. This tells
       * an output console that it has input ready.
      class ConsolePrintStream extends PrintStream {
        Object lock;
        public ConsolePrintStream(Object lock, OutputStream out) {
          super(out);
          this.lock = lock;
        public void write(byte[] buf,
                          int off,
                          int len) {
          synchronized(lock) {
            lock.notify();
            super.write(buf,off,len);
       * A class that extends PrintStream to throw away all
       * input sent to it. This is used to supress standard out
       * and speed up test model runs with debugging output
      class NullPrintStream extends PrintStream {
        public NullPrintStream(OutputStream out) {
          super(out);
        public void write(byte[] buf,
                          int off,
                          int len) {
      public void suppressStandardOut() {
        // create a dumby temp file to use as an output stream
        // nothing will ever actually be written to the file
        try {
          File dumbFile = File.createTempFile("notme", "not1337");
          dumbFile.deleteOnExit();
          PrintStream out = new NullPrintStream(new FileOutputStream(dumbFile));
          System.setOut( out );
          System.setErr( out );
        } catch(IOException ioe) {
          System.out.println("Error supressing standard out");
          ioe.printStackTrace();
      public void availableStandardOut() {
        System.setOut( consoleOut );
        System.setErr( consoleOut );
      private void setupOutput() {
        Thread printer = new Thread( new Runnable() {
            public void run() {
              PipedInputStream pipe = new PipedInputStream();
              BufferedReader in = new BufferedReader
                (new InputStreamReader( pipe ));
              try {
                PipedOutputStream pipeOut = new PipedOutputStream(pipe);
                consoleOut = new ConsolePrintStream(lock, pipeOut);
                System.setOut( consoleOut );
                System.setErr( consoleOut );
              catch (Exception e) {
                System.out.println("Failed to create Pipe for System.out");
                e.printStackTrace();
                return;
              try {
                for(;;) {
                  while(!in.ready()) {
                    synchronized(lock) {
                      lock.wait();
                  text.append(in.readLine()+"\n");
                  verticalScrollBar.setValue(verticalScrollBar.getMaximum());
              } catch (Exception e) {
                System.out.println(e);
                e.printStackTrace();
        printer.setDaemon(true);
        printer.start();
    }

  • Using ajax/servlets, different behaviour with different systems

    I have written a small web application using servlets and ajax. I used the tomcat bundled with netbeans for deploying it. In the front end I create a timer which keeps running. I also have a form containing a paragraph that displays a question, followed by radio buttons and two buttons - a next and a submit. When I click the next button, I call a javascript function that creates an xmlHttp Object and sends the request for the next question and options from the servlet. when I request I also pass what the user has selected for the current question. when the timer reaches twelve or the user has finished attending all questions, the function would request for score through another xmlHttp Object. This program works fine in my computer. I also installed another tomcat server and ran it on another port and tested it. It works fine. But when I ran it college, the page was not displayed properly. When I click an option the contents of the form moves and only when I click the Next button twice, the corresponding javascript function is called.
    I am pasting the html file and the servlet. What could be the reason?
    This is qns.html
    <html>
      <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    //styles
        <script type ="text/javascript">
            <!--
            var no_of_qns = 2;
            var s = 1;
            var m = 0;
            var h = 0;
            var jsqno = 0;
            var flag = 0;
            var jsnds;
            var jmin;
            var sid;
            var cont;
            var oldhtml;
            function load(){
                cont = document.getElementById('container');
                oldhtml = cont.innerHTML;//backup the content to display it after the user accepts the rules
                var ins = "<ul><li>You have to complete 30 qns in 30 mins</li><li>Click finish to quit</li><li>All the best</li></ul>";
                cont.innerHTML = "<p style =\" text-align: center; font-size : 17px \">Instructions</p>"+ins+"<form action=\"javascript:funct()\"><input type=\"submit\" value = \"I have read the instructions\"></form>";
            function funct(){
                    //alert('why?');
                    cont.innerHTML = oldhtml;//replace back the question after user has accepted to the terms and conditions.
                    sid = setInterval("updateClock()",1000);
                    ajaxFunction(0);
            function ajaxFunction(chz)
                jsnds = document.getElementById('snds');
                jmin = document.getElementById('min');
               var back;
                var ans = 'arunkumar c';
                try
                    var xmlHttp=new XMLHttpRequest();
                catch (io)
                    alert("Your might be using IE or your browser does not support AJAX!.");
                    return false;
                xmlHttp.onreadystatechange=function()
                    if(xmlHttp.readyState==4)
                           // Get the data from the server's response
                           back = xmlHttp.responseText;
                           if(flag == 0){
                                var values = back.split("|");
                                document.getElementById("question").innerHTML=values[0];
                                document.getElementById("choicea").innerHTML=values[1];
                                document.getElementById("choiceb").innerHTML=values[2];
                                document.getElementById("choicec").innerHTML=values[3];
                                document.getElementById("choiced").innerHTML=values[4];
                                return true;
                                else{
                                    //alert('what');
                                    document.getElementById("container").innerHTML = "<p>You have completed the test and your score is "+back+".</p><p><a href=\"/OnlineApti/login.html\">Go Back</a> to login page! Thank you!";
                if(uform.choice[0].checked == true){
                    ans = document.getElementById("choicea").innerHTML;
                else if(uform.choice[1].checked== true){
                    ans = document.getElementById("choiceb").innerHTML;
                else if(uform.choice[2].checked == true){
                    ans = document.getElementById("choicec").innerHTML;
                else if(uform.choice[3].checked == true){
                    ans = document.getElementById("choiced").innerHTML;
                if(chz == 1){
                    jsqno = no_of_qns;
                if(jsqno == no_of_qns)
                    clearInterval(sid);
                     //alert(clearInterval(sid));
                     flag = 1;
                jsqno = jsqno + 1;
                var url = "http://localhost:8084/OnlineApti/test";
                url = url+"?qno="+jsqno+"&ans="+ans;
                //alert(url);
                xmlHttp.open("GET",url,true);
                xmlHttp.send(null);
            function updateClock(){
                //alert('why');
                s++;
                jsnds.innerHTML=" "+s;
                if(s == 60){
                    m++;
                    s = 0;
                    jmin.innerHTML =" "+m;
                //alert("http://localhost:8084/OnlineApti/test?qno="+(no_of_qns+1)+"&ans=final");
                if(m == 30){
                    alert ('The quiz is over!! You failed to complete it within the time limit');
                    var xmlHttp;
                    try
                        xmlHttp=new XMLHttpRequest();
                    catch (io)
                        alert("Your might be using IE or your browser does not support AJAX!.");
                        return false;
                    xmlHttp.onreadystatechange=function()
                        if(xmlHttp.readyState==4)
                            var back = xmlHttp.responseText;
                            document.getElementById("container").innerHTML = "<p>You have completed the test and your score is "+back+".</p><p><a href=\"/OnlineApti/login.html\">Go Back</a> to login page! Thank you!";
                    xmlHttp.open("GET","http://localhost:8084/OnlineApti/test?qno="+(no_of_qns+1)+"&ans=final",true);
                    xmlHttp.send(null);
                    clearInterval(sid);
      //-->
      </script>
      </head>
      <body onload="load()">
        <div class="top">
         <h1>Welcome to Online Quiz</h1>
        </div>
        <div class="main" id="container">
            <form name ="uform" action="javascript:ajaxFunction(1)">
            <table cellpadding ="5" cellspacing ="20">
                <thead></thead>
                <tbody>
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td align="right">
                            <p style="text-align:right" id="clock">Time: 0:<span id="min">0</span>:<span id ="snds">0</span></p>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="4">
                            <p id="question"></p>                 
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <input type="radio" name ="choice"><span id="choicea"></span>
                        </td>
                        <td>
                            <input type="radio" name ="choice"><span id="choiceb"></span>
                        </td>
                        <td>
                            <input type ="radio" name ="choice"><span id="choicec"></span>
                        </td>
                        <td>
                            <input type ="radio" name="choice"><span id="choiced"></span>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <input type ="button" value ="Next" name ="nxt" onclick="ajaxFunction(0)">
                        </td>
                        <td colspan="2">
                            <input type = "submit" value ="Finish">
                        </td>
                    </tr>
                </tbody>
            </table>
        </form>
        </div>
      </body>
    </html>
    import java.io.*;
    import java.net.*;
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.lang.*;
    * @author arun
    public class test extends HttpServlet {
        * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
        * @param request servlet request
        * @param response servlet response
            Connection con;
            int marks = 0;
            StringBuffer qn;
            int qno;
            String prevAns = "wow";
            String choice = new String();
            //To be updated based upon the number of questions!!
            int no_of_qns = 2;
        public void init(ServletConfig config) throws ServletException {
            try {
                Class.forName("org.gjt.mm.mysql.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "");
                Statement qry;
                qry = con.createStatement();
                qry.executeQuery("use login;");
            } catch (Exception io) {
                System.out.println(io);
                System.exit(0);
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            qn = new StringBuffer();
            try {
                Statement qry;
                qry = con.createStatement();
                qno = Integer.parseInt(request.getParameter("qno"));
                choice = request.getParameter("ans");
                if(prevAns.equalsIgnoreCase(choice)){
                      marks++;               
                if(qno == (no_of_qns +1)){
                    out.println(marks);
                    marks = 0;
                String qryString = "select * from questions where questionno="+qno+";";
                ResultSet rs = qry.executeQuery(qryString);
                while(rs.next()){
                    qn.append(rs.getString(1));
                    qn.append(") "+rs.getString(2));
                    qn.append("|"+rs.getString(3));
                    qn.append("|"+rs.getString(4));
                    qn.append("|"+rs.getString(5));
                    qn.append("|"+rs.getString(6));
                    prevAns =rs.getString(7);
                out.println(qn.toString());
            catch(SQLException io){
                System.out.println(io);
            finally {
                out.close();
        // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
        * Handles the HTTP <code>GET</code> method.
        * @param request servlet request
        * @param response servlet response
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
        * Handles the HTTP <code>POST</code> method.
        * @param request servlet request
        * @param response servlet response
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
        * Returns a short description of the servlet.
        public String getServletInfo() {
            return "Short description";
        // </editor-fold>
    }What might be the problem?
    Edited by: carunkumar on Oct 4, 2008 8:21 AM

    carunkumar wrote:
    function ajaxFunction(chz)
    jsnds = document.getElementById('snds');
    jmin = document.getElementById('min');
    var back;
    var ans = 'arunkumar c';
    try
    var xmlHttp=new XMLHttpRequest();
    catch (io)
    alert("Your might be using IE or your browser does not support AJAX!.");
    return false;
    }First thing is that the Ajax request you are building is not browser specific.
    Go to this site it will give you the specific code www.tizag.com/ajaxTutorial/
    And do try and test your program on diff browser from your pc only. Its a ajax world so be careful while dealing with browsers
    and there settings. Just check your browser setting on your pc and check the same setting at your college also.
    Buddy this ajax give a trick in big presentation also :) So no need to worry and test it and do it, its real fun when you just
    cross this browser secific dependencies.
    Cheers
    Sachin Kokcha

  • 32-bit JDK 7 System.out.println not working in IDE

    Hi folks,
    I have a 64-bit Windows 7 OS.
    Due to 3rd party library/jar dependencies, i had to install the 32-bit Java JDK 1.7 and Eclipse IDE.
    I also installed NetBeans.
    So i have a 64-bit OS and am running 32-bit Java JDK/JRE & IDEs.
    The problem I am having is that my program's System.out.println("...") statements are not outputting strings to either IDE debug console.
    Executing the compiled program from a command line/prompt produces the expected string output.
    The basic "Hello, World" program is enough to cause this behaviour to start occurring.
    I have not manually / intentionally changed any IDE-specific Debug Console or Windows environment settings.
    One caveat: This same environment has worked successfully in the past ?! Yes, this is one of those "..it worked last week & yesterday and today it isn't and i swear i didn't do anything..." issue.
    Thoughts ?

    Thanks for the reply.
    The 64-bit versions of Java & Eclipse were installed first.
    When i discovered I had to use the 32-bit versions, i un-installed the 64-bit ones & installed the 32-bits.
    Even after that initial un-install 64-bit/install 32-bit process, it was working.
    I have also been installing the Windows 7 64-bit OS updates when i am informed of them.
    I'm not sure if any of these would affect how the Eclipse / NetBeans IDEs behave.
    Behaviour has been inconsistent.
    Initially it was always working.
    But over the past several days, it has been working less and less.
    I don't have any large data structures.
    This isn't a large complicated program, couple hundred lines, so i highly doubt that i'm doing anything to the resources, but something has changed.
    The main project I am working on takes command line parameters, does some initial processing, produces output using System.out.printlns [SOP] then depending on the parameters, branches into 2 different processing paths, let's call them A & B. Each of these processing paths also use SOPs. When i run the program in the IDE going thru path A, sometimes the initial SOP statements will work and the SOP statements specific to path A will also work. If i immediately change the parameters to go thru path B & re-run it, not even the initial SOP statements before the branching decision work.
    I've tried doing System.flush()s too - no affect.
    I haven't tried the re-direction option to a file option you mentioned yet.
    It always works from a command prompt - that is telling me that the Java SOPs are working properly, correct ?
    Inside an Eclipse or NetBeans IDE, SOP output to the debug console is inconsistent.
    Running from a command prompt, the SOPs always work.
    It'd help to know if this an IDE issue, a Java issue, a Windows 7 issue so i can narrow down where to try and correct the situation.
    I have a Windows XP VM set up, i'll try running the program there and see if there's a difference.
    Thanks for your reply.

  • How can i put a system.out.println into txt file

    i want to generate a txt file instead of system.out.println. for the output How can i do that and what code can i use for that??
    Edited by: crystalarun on Oct 14, 2007 11:40 AM

    suppose u ant output in "Output.txt"
    then code can be
    PrintStream out = new PrintStream(new FileOutputStream("Output.txt"));
    System.setOut(out)

  • System.out.println () is not working properly

    Hi, Why does this happens:
    Object temp=null;
    System.out.println ("temp is null? "+temp==null);
    just prints: true
    expected: temp is null? true
    Why does this happens????
    If I do System.out.println ("temp is null? "+(temp==null)); it works bu it should work without the pharentesis too

    MelGohan wrote:
    Hi, Why does this happens:
    Object temp=null;
    System.out.println ("temp is null? "+temp==null);
    just prints: trueThat is odd, mine prints "false".
    type Test126.java
    public class Test126 {
        public static void main(String[] args) {
            Object temp=null;
            System.out.println ("temp is null? "+temp);
            System.out.println ("temp is null? "+temp==null);
    }javac Test126.java
    java Test126
    temp is null? null
    false

  • Strange System.out.print behavior inside a for loop

    I'm trying to create a simple ASCII progress bar in the console that would display like this:
    |--------------------------------------------|
    ============================More equal signs would appear as time goes on. At least this is what I want to happen.
    Instead, what happens is, none of the equal signs are printed until the very end, after the for loop in which the System.out.print("=") statement is in, has exited.
    This is my code (probably more than necessary is shown, but the important part is the for loop):
        public void addSomeDiffys(int numOfDiffys, int minInt, int maxInt) {
            Diffy currentDiffy;
            System.out.println("\nCreating Diffys.");
            System.out.println("|--------------------------------------------|");
            for (int i=0; i < numOfDiffys; i++) {
                currentDiffy = new Diffy(minInt, maxInt);
                if ((i/(double)numOfDiffys)*100 % 2 == 0)
                    System.out.print("=");
                diffyList.add(currentDiffy);           
            System.out.println("\n" + diffyList.size() + " Diffys created.\n");
            System.out.println("Sorting according to highest rating...");
            Collections.sort(diffyList,Diffy.HIGHEST_RATING_ORDER);
            System.out.println("Done.\n");
        }I also tried changing the System.out.print("="); to System.out.println("="); This time it works as expected, its just not very pretty...
    I get something like this:
    |--------------------------------------------|
    =
    =
    =
    =
    =
    =
    =
    =
    =
    =
    =
    =So again, when I use println, rather than print, the equal signs are printed over time, slowly, as the progress increases. When using print, Nothing happens for a long time, and then suddenly they all appear after the for loop has terminated, which makes no sense.
    Thanks for any help.

    When using print, Nothing happens
    for a long time, and then suddenly they all appear
    after the for loop has terminated, which makes no
    sense.
    Yes it does make sense! The characters are buffered inside the PrintStream and written when there is a full line to write. You could try a flush() after each = is written but I have no confidence that it will make any difference.

Maybe you are looking for

  • High Pass Dialog Textbook Exercise

    I purchased the Power, Speed and Automatitation textbook to learn Photoshop Scripting. I am working through the exercises in the last chapeter Building Custom Dialogs and have stumbled on the last exercise building a High Pass Dialog. When I test the

  • Connecting RGB/VGA monitor to ADC connector on G4

    I've got a G4 that has a Nvidia GeForce2 MX video card with an ADC and RGB/VGA connectors on it. The RGB/VGA connection is completely broken. I have hooked up 5 monitors to it and they are all awful looking with color problems and major banding all o

  • Can I use a modem I got from a friend with Verizon DSL?

    My friend gave me a Verizon DSL (modem plus router) for Verizon. Can I use that for DSL service? Thanks!!!

  • Migration or any other procedure to do the needful

    We are looking to migrate out Oracle 8 database to the latest database. How complex is the process going to be . The oracle 8 database is on a Windows server and has to be migrated to the latest version on the windows server machine. Can anyone pleas

  • Decimal Field Pattern limit to 2 decimals only

    Hi, I am want to limit a numeric field to 4 leading digits and only 2 trailing digits, example 1,234.59. I have set this pattern up in the Display pattern: num{z,zz9.99}|num{z,zz9.zz}|num.currency{}. The problem is if the user enters less than 4 lead