Reading System out stream ?

Hi,
I don't know whether I am asking a stupid question or not . But my problem is that in my thousand lines of code i wrote number of System.out.println(".....") statements to describe various situations / state of program which write those strings of messages to standard output i.e console . Here at this point of situation I was wondering that is there a possible way that i could read System.out stream by concurrently running a thread who could look on this stream and could redirect it to a file where i want. By achieving this I don't need to go at every piece of code where i have written System.out.println(".....") and change it to get desired result.
If it is possible , please let me know ?
Thanks in advance,
Hemant.

A suggestion - next time, set up a boolean - call it maybe "debugFlag" and check it befor a system.out write. That way all that's needed is to reset the flag and recompile when it goes to "production".
And then the other possibility is to use your editor and do some global change all in your code.

Similar Messages

  • Is System.out stream synchronized?

    Hi,
    I am using the System.out stream to print various logging messages
    by different threads.
    I am using System.out.println
    Is this thread-safe?
    The messages themselves are only for development, they are not essential,
    that's why I haven't bothered to set up any synchronization mechanism...

    Hi,
    are you sure?
    On what grounds do you claim this?
    The Javadocs do not specify it.
    Thanks.If you question the correctness, it's time for you to do your own research.

  • Redirecting System.out stream to a TextArea

    I hope this isn't a stupid question--I'm blanking pretty hard.
    I want to use System.setOut() to direct standard output to a TextArea within a Frame. Is there a way to setup a TextArea to receive text from an output stream, or is an intermediary of some sort necessary?
    I feel like this is pretty easy, but I'm stumbling. That's what I get for doing J2EE for a year rather than GUI. :P
    Any input is appreciated!

    Here's the compiled and tested code...I learned some good stuff from this link as to why my simpler approach didn't work:
    http://www.devx.com/upload/registered/features/javapro/1999/11nov99/tl1199/tl1199.asp
    Here is my code:
      class OutRouter implements Runnable
        PipedInputStream pipeIn = null;
        JTextArea textArea = null;
        OutRouter( JTextArea ta, PipedOutputStream pos)
          try
            pipeIn = new PipedInputStream(pos);
          catch(IOException ioe)
            ioe.printStackTrace(System.err);
            System.exit(1);
          textArea = ta;
        public void run()
          String line = null;
          BufferedReader pipeReader = new BufferedReader(
            new InputStreamReader(pipeIn));
          try
            while(true)
              Thread.sleep(100);
              if(pipeIn.available() == 0)
                continue;
              line = pipeReader.readLine();
              if(line == null)
                continue;
              System.err.println("Line = " + line);
              final String fLine = line;
              SwingUtilities.invokeAndWait( new Runnable()
                {public void run()
                  { textArea.append(fLine + "\n"); }
          catch(InvocationTargetException ite)
          { ite.printStackTrace(System.err); System.exit(1); }
          catch(InterruptedException ie)
          { ie.printStackTrace(System.err); System.exit(1); }
          catch(IOException ioe)
          { ioe.printStackTrace(System.err); System.exit(1); }
      }

  • To redirect System.out stream output on swing's JTextArea

    Following is a program that needs to print output as follows:-
    EXPECTED OUTPUT ON GUI:_ In action block (datapayload value) In Routing block (argus value)
    PRESENT PROGRAM OUTPUT ON GUI_ In action block (datapayload value)
    please examine the below code and correct mistakes to get the expected output as given above.....
    I am not getting the second line as output on GUI i.e., In Routing block (argus value)
        import java.awt.*;
        import javax.swing.*;
        import java.awt.event.*;
        import java.io.*;
        public class Demo extends JFrame implements ActionListener
          JTextField datapayload;
          JLabel Datapayload;
          JButton submit;
          JTextArea textFieldName;
          public Demo()
             DemoLayout customLayout = new DemoLayout();     
             getContentPane().setFont(new Font("Helvetica", Font.PLAIN, 12));
             getContentPane().setLayout(customLayout);
             Datapayload = new JLabel("Enter DataPayload:");
             getContentPane().add(Datapayload);
             datapayload = new JTextField("abcd...");
             getContentPane().add(datapayload);
             submit = new JButton("submit");
             getContentPane().add(submit);
             textFieldName = new JTextArea(80,10);
             textFieldName.setEditable( false );
             JScrollPane scroll = new JScrollPane(textFieldName) ;
             scroll.setBounds( 10, 60, 225, 150 );
             getContentPane().add( scroll );
             submit.addActionListener(this);
             setSize(getPreferredSize());
           public void actionPerformed(ActionEvent e)
              String demodata=datapayload.getText();
                 textFieldName.append("In Action Block"+"\t"+demodata);  
              Demo pr = new Demo();                              
              pr.DemoRoute(demodata);
           public void DemoRoute(String argus)
                 textFieldName.append("In routing block"+"\t"+argus);
            public static void main(String args[])
                 Demo window = new Demo();
                 window.setTitle("Demo");
                 window.pack();
                 window.show();
        class DemoLayout implements LayoutManager
           public DemoLayout() {  }
           public void addLayoutComponent(String name, Component comp) {   }
           public void removeLayoutComponent(Component comp) {  }
           public Dimension preferredLayoutSize(Container parent)
             Dimension dim = new Dimension(0, 0);
             Insets insets = parent.getInsets();
             dim.width = 320 + insets.left + insets.right;
             dim.height = 240 + insets.top + insets.bottom;
             return dim;
           public Dimension minimumLayoutSize(Container parent)
             Dimension dim = new Dimension(0, 0);
             return dim;
           public void layoutContainer(Container parent)
             Insets insets = parent.getInsets();
             Component c;
             c = parent.getComponent(0);
             if (c.isVisible()) {c.setBounds(insets.left+90,insets.top+8,172,26);}
             c = parent.getComponent(1);
             if (c.isVisible()) {c.setBounds(insets.left+230,insets.top+8,172,26);}
             c = parent.getComponent(2);
             if (c.isVisible()) {c.setBounds(insets.left+230,insets.top+52,142,26);}
             c = parent.getComponent(3);
             if (c.isVisible()) {c.setBounds(insets.left+90,insets.top+100,472,268);}
        }  Edited by: 997189 on Mar 31, 2013 8:52 AM

    Hi,
    change your actionPerformed() method as below to get the required output.
    public void actionPerformed(ActionEvent e)
              String demodata=datapayload.getText();
                 textFieldName.append("In Action Block"+"\t"+demodata);  
              //Demo pr = new Demo();      You are creating a new object to all DemoRoute method. This is the problem                         
              //pr.DemoRoute(demodata);
                 this.DemoRoute(demodata);
    }And also my suggestion is follow java coding conventions while coding

  • Redirect system.out.println() to a file

    hi all,
         how can i redirect all the console prints to a txt file in java application? i have used system.out oftenly in many class throught the
    application. is there any way to redirect all those console prints to a
    txt file by converting or assigning the System.out stream to a stream for filewriter or
    somthing like that, so that whenever system.out.println() is executed
    the content is written to a file insted of on the console.
    thanks in advance
    Sojan

    Actually,System.setOut(new PrintStream(new FileOutputStream("output.txt"), true));
    System.setErr(System.out);since setOut wants a PrintStream and not just some OuputStream...

  • 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();
    }

  • System.in.read and System.out.print questions

    On the following code, two questions:
    1. the output is not what I expected. Why doesn't the System.out.println(i+" "+(char)i); print everytime i press enter a character? It seems to print all at once after everything is entered.
    package stars;
    import java.io.*;
    public class Stars {
      public static void main (String[] args) throws IOException {
        String U="";
        System.out.print("What is your name: ");
        while (true) {
          int i=System.in.read();
          U+=(char)i;
          System.out.println(i+" "+(char)i);
          System.out.flush();
          if (i==10||i==13) break;
        System.out.println("\rHello "+U);
    }C:\>java -cp . stars/Stars
    What is your name: blah
    98 b
    108 l
    97 a
    104 h
    13
    Hello blah
    2. What is the most natural way to check for the press of an enter key? Is there a java attribute or method for the "Enter key" since it is different on unix and ms-dos? Thanks

    On the following code, two questions:
    1. the output is not what I expected. Why doesn't
    the System.out.println(i+" "+(char)i); print
    everytime i press enter a character? From:
    http://scv.bu.edu/Doc/Java/tutorial/java/nutsandbolts/input.html
    ================
    "The read() method provided by System.in reads a single character and returns either the character that was read or, if there are no more characters to be read, -1.
    When a program reads from the standard input stream, the program blocks waiting for you to type something in. The program continues to wait for input until you give it some indication that the input is complete. To indicate to any program that reads from the standard input stream that you have finished entering characters, type the end-of-input character appropriate for your system at the beginning of a new line"
    ================
    In other words, Java can't do what you want to do.
    <snip>
    >
    2. What is the most natural way to check for the
    press of an enter key? Is there a java attribute or
    method for the "Enter key" since it is different on
    unix and ms-dos? Thanks
    System.getProperty("line.separator");Jim S.

  • How does one intercept System.out.println stream.

    If you want some functionality wherein when you call System.out.println - the stream gets written to System.out AND additionally does something else (e.g. send mail).
    AND
    You do not want to write a new class/method to do so and replace all System.out.println in your source base with this new class/method;
    Then how would you be able to achieve this. Thanks in advance.

    Here is the basic code, you may need to tune performance. I havent compiler or tested it, but it should give you a good idea.
    public class OutputStreamCollection extends OutputStream{
    private OutputStream[] outs = new OutputStream[0];
    public synchronized void addOutputStream(OutputStream argOut) {
    OutputStream[] old = outs;
    outs = new OuputStream[old.length + 1];
    System.arraycopy(old,0,outs,0, old.length);
    outs[outs.length - 1] = argOut;
    public syncrhonized void write(int data) {
    for(int i = 0; i < outs.length; i++) {
    outs.write();
    public synchronized void write(byte[] data, int offset, int length) {
    for(int i = 0; i < outs.length; i++) {
    outs[i].write(data, offset, length);
    nor the following code, will print and log to respective files whatever is going to stdout or stderr
    OutpputStreamCollection out = new OutputStreamCollection();
    out.addOutputStream(System.out);
    out.addOutputStream(new FileOutputStream("stdout.log"));
    System.setOut(out);
    OutpputStreamCollection err = new OutputStreamCollection();
    out.addOutputStream(System.err);
    out.addOutputStream(new FileOutputStream("stderr.log"));
    System.setOut(err);
    you can write adapter classes to process the stream in any way you need, like logging with log4J, or sending mail depending on some crieteria.
    Hope it helps.

  • ERROR while saving the runtime systems(read time out exception)

    Hi e xperts
    I am configuring NWDI and assigned asll the permissions and roles to the CMS user.I created Domain,in landscape configurater
    created track and saved.
    while saving the rumtime systems the error thrown is
    com.sap.cms.util.exception.conf.CMSCCBSCommunicationException: CBS (URL http://dtlepdev:54400/tc.CBS.Appl/archiveapi2/) communication exception: Read timed out (Service call exception; nested exception is:
    java.net.SocketTimeoutException: Read timed out)
    at com.sap.cms.pcs.conf.communicator.CBSConfCommunicator.removeBuildspace(CBSConfCommunicator.java:382)
    at com.sap.cms.pcs.conf.communicator.CBSConfCommunicator.deleteCreateBuildspace(CBSConfCommunicator.java:338)
    at com.sap.cms.pcs.conf.communicator.CBSConfCommunicator.editBuildspace(CBSConfCommunicator.java:277)
    at com.sap.cms.pcs.conf.communicator.CBSConfCommunicator.createBuildspace(CBSConfCommunicator.java:168)
    at com.sap.cms.pcs.conf.core.services.SystemManagerObject.saveSystem(SystemManagerObject.java:261)
    at com.sap.cms.pcs.conf.core.plugin.DefaultTrack.newTrack(DefaultTrack.java:292)
    at com.sap.cms.pcs.conf.core.TrackManager.editTrack(TrackManager.java:208)
    at com.sap.cms.pcs.conf.manager.CmsConfManager.editTrackConfiguration(CmsConfManager.java:1002)
    at com.sap.cms.pcs.conf.manager.proxy.CmsConfProxyBean.editTrackConfiguration(CmsConfProxyBean.java:489)
    at com.sap.cms.pcs.conf.manager.proxy.LocalCmsConfProxyLocalObjectImpl0_0.editTrackConfigurationand also ..
    Unable to instantiate a Build Space administrator!
    Build Space "DTL_ETRACK_C" [bsID: 27, version: 0] [in-queue: on (privileged), out-queue: "on", processing: off]
    <null>
    [EXCEPTION]
    Buildspace DTL_ETRACK_C does not own the workspace ws/ETRACK/dtl.com_DEFAULTIME/cons/inactive/ .  It is currently not owned by any other buildspace
    at com.sap.tc.cbs.server.rt.bs._BuildSpaceValidator.checkWorkspace(_BuildSpaceValidator.java:120)
    at com.sap.tc.cbs.server.rt.bs._BuildSpaceValidator.validateWSs(_BuildSpaceValidator.java:74)
    at com.sap.tc.cbs.server.rt.bs.BSAdmin.validate(BSAdmin.java:192)
    at com.sap.tc.cbs.server.rt.bs.BSAdmin.updateState(BSAdmin.java:260)
    at com.sap.tc.cbs.server.rt.bs.BSAdminOrc.determineChanges(BSAdminOrc.java:439)
    at com.sap.tc.cbs.server.rt.bs.BSAdminOrc.validateBuildSpaceData(BSAdminOrc.java:219)
    at com.sap.tc.cbs.server.rt.bs.BSAdminOrc.act(BSAdminOrc.java:341)
    at com.sap.tc.cbs.server.rt.impl.CourteousTimer.run(CourteousTimer.java:139)
    at java.lang.Thread.run(Thread.java:534
    In cbs i checked the parametrs they are open and on..
    please suggest me on this ASAP..since 2 days i have been struggling and searched in forums..no perfect solution
    help me out
    perfect soln is immediately awarded...
    I
    THanks
    Mayu

    Hi Mayu,
    here apparently the CMS cannot communicate to CBS properly and then when CMS tries to talk to CBS using a webservice, it times out due to various reasons, see below.
    Strange, I always had this error when the CMS was on a different release like CBS and this caused the communication problem.
    Don't you have an entry in your cms log like this?
    com.sap.cms.util.exception.CMSUnexpectedException                          
    at com.sap.cms.pcs.conf.manager.CmsConfManager.newTrackConfiguration(CmsConfManager.java:666)                                                    
    Caused by: java.lang.IncompatibleClassChangeError
    at com.sap.cms.pcs.conf.communicator.CBSConfCommunicator.openConnection(CBSConfCommunicator.java:84)                                             
    Please provide me the version of the DI_CMS, DI_CBS (and DI_DTR for the sake of completeness).
    You can find this info on the ComponentInfo page.
    On 640/700 this is http://<host>:<port>/sap/monitoring/ComponentInfo
    as of 710 you find this on the "Components" tab of http://<host>:<port>/nwa/sysinfo
    I also think that this is not due to the runtime systems. I guess you have the same problem if you try to create the track without runtime systems, right?
    (The "Unable to instantiate a Build Space administrator!" is not necessarily an error, see the note:
    #1175019 - Unable to instantiate a Build Space administrator!)
    Thank you!
    Best Regards,
    Ervin

  • Large file read in, system out error!

    the following method simply reads 6MB text file by each line.
    After reading a line, separate the line with '\t', and obtain 2 tokens.
    After getting 2 tokens, synthesis the 2 tokens into another string token.
    Sythesized token is displayed with System.out.println().
    However, I can't have all contents from the input file, and I can't dispaly all of them in monitor screen, either.
    What's wrong with my code?
    PS: each line of the input file is structured by "key\tcontent\n" , and the number of lines is 400000.
    ===========
    public void makeDictionary(){
    String line;
    try{
    BufferedReader in = new BufferedReader( new FileReader(filePath));
    while( (line = in.readLine()) != null ){
    String key;
    String content;
    int index = line.indexOf('\t');
    key = line.substring(0, index);
    content = line.substring(index+1, line.length());
    System.out.println( key + "\t" + content );
    System.out.flush();
    in.close();
    catch( Exception e){}
    }

    Thank you for your answer.
    I can't enough thank you.
    Actually, I used try..catch structure for my code, however I didn't get any message from catch block. In addition to this, the process didn't stop; in other word, the process was going on while doing nothing. I monitored the utilizaton of CPU and memory. The utilization of CPU was 100%, but after a while, it was 0%, even though process was still alive. The state which the process was doing nothing continued forever.
    Frankly speaking, I used this code for constructing my own data structure from a large text file. While debugging my code, I realized that the method, readLine() of BufferedReader class didn't load all the data of the input file, so I made the code for testing.
    Anyway, I am just fully depending on your answer. Please help me!!!!
    Your quick response will be appreciated.

  • Here's a dumb ? I'm trying to find out how I can print from my ipad. I read about air streaming printers. so is a wireless printer considered an air streaming printer. i have 1 pc, my mac

    here's a dumb ? I'm trying to find out how I can print from my ipad. I read about air streaming printers. so is a wireless printer considered an air streaming printer. i have 1 pc, my mac

    If you already have a printer, you can probable use a program like, printopia to let your mac share your printer with the iOS device like your iPad. The catch being your computer has to be on, and not asleep, for the printer to work with your iPad.
    If you need a printer that is airprint ready, you can find a list on AirPrint, wireless printing straight from your iPad. Check out the bottom of the page where it says works with airprint enabled printers. There are even links on the page so you can buy the printers right from Apple's website.

  • How to capture System.out, done by another program

    Hi All,
    My application runs other application in back. How can I capture system.out.println() written by another application & display via dialog box.
    Like :execl() or execv() function in C runtime library. Where every printf() message printed to passed buffer.
    Thank you,
    Avin Patel

    You can create an InputStream from a started process. Then read all the bytes from the inputstream and write them to an outputstream (like System.out)
    Process p = Runtime.getRuntime().exec(COMMAND);
    InputStream is = p.getErrorStream();   //Or another stream
    int[] buffer = new int[128];
    while((read = is.read(buffer)) != -1){
    System.write.out(buffer, 0, read);
    }

  • Server Socket does not read data input stream

    Hi all,
    I am very newbie to Java Network programming with sockets and multi-threading.
    But I am obliged to develop a chat system written in Applets which can be placed on the website and used by visitors who come to my website.
    In order to understand this, I have tested a basic web chat program I downloaded from the Internet which use sockets and multi-threadings. The program work fine, no bugs at all at both compilation and run time. I noticed that all three streams for Client side (i.e. first one is input stream used receiving data from User; the second one is socket input stream used for receiving data from Server socket, and the third is socket output stream used for writing data to server socket) were established. And the same, two socket streams (input & output) for Server side were also connected when running program giving right port number and IP address of the server.
    The problem is both server and client sockets do not read data using the following stream classes:
    1. DataStreamInput: I use input.readUTF() method
    2. or BufferedReader: I use input.readLine() method
    The example of the codes are below:
    private BufferedReader input = null;
    private PrintWriter output = null;
    private Socket socket = null;
    public void open() throws IOException
    {  input = new BufferedReader(new
    InputStreamReader(socket.getInputStream()));
    System.out.println("Server socket input stream was created, and");
    output = new PrintWriter(socket.getOutputStream());
    System.out.println("Server socket output stream was created");
    public void run()
    {  System.out.println("Server Thread " + clientPort + " running.");
    while (true)
    {  try
    System.out.println("Server is reading data from Client, wait...");
    String fromClient = input.readLine();
    System.out.println("Server received a message on " + clientPort + ".");
    catch(IOException ioe)
    {  System.out.println(clientPort + " ERROR reading: " + ioe.getMessage());
    server.remove(clientPort);
    stop();
    The problem is at the line: String fromClient = input.readLine(); in the run() method? What is wrong with the codes above?
    Note: I also try to use original codes which use readUTF() method in DataStreamInput class instead using readLine() in BufferedReader. Both methods dont read data from inputstream socket?
    I very appreciate any help/advice from experienced developers.
    Best regards

    Hi,
    Yes. The readLine() method hangs! After the test, the execuation of the program is stopped at the line of readLine() method; it does not pass it?
    There is no problem with writing to Server socket. After the test, the program pass through flush() method. Here is the code for writing to sever socket within ChatClient (client side socket) class:
    private BufferedReader input = null;
    private PrintWriter           output = null;
    public ChatClient(String serverName, int serverPort)
    {  System.out.println("Establishing connection. Please wait ...");
    try
    {  socket = new Socket(serverName, serverPort);
    System.out.println("Connected: " + socket);
    start();
    catch(UnknownHostException uhe)
    {  System.out.println("Host unknown: " + uhe.getMessage()); }
    catch(IOException ioe)
    {  System.out.println("Unexpected exception: " + ioe.getMessage()); }
    public void start() throws IOException
    {  input   = new BufferedReader (new
                             InputStreamReader(System.in));
    System.out.println("Client User input stream was created,");
    output = new PrintWriter(socket.getOutputStream());
    System.out.println("Client Socket output stream was established, and");
    if (thread == null)
    {  client = new ChatClientThread(this, socket);
    thread = new Thread(this);
    thread.start();
    public void run()
         while (thread != null) {
         String fromUser;
              try{
                   while((fromUser = input.readLine())!= null)
                   System.out.println("Client wasreading a data from User, and");
    output.println(fromUser);
         output.flush();
         System.out.println("Client has written a data to Server");
    catch(IOException ioe)
    {  System.out.println("Sending to server error: " + ioe.getMessage());
    stop();
    etc.
    Here is a piece of codes for reading data from the Client Socket in the ChatServer Class (Server Side socket):
    public void run()
    {  System.out.println("Server Thread " + clientPort + " running.");
    while (true)
    {  try
    {  //server.handle(clientPort, input.readLine());
    System.out.println("Server is reading data from Client, wait...");
    String fromUser = input.readLine();
    //while((fromUser = input.readLine()) != null)
         System.out.println("Server received a message on " + clientPort + ".");
    catch(IOException ioe)
    {  System.out.println(clientPort + " ERROR reading: " + ioe.getMessage());
    server.remove(clientPort);
    stop();
    etc. Please advice why the readLine() method hangs; does not read data from the input stream received from the CLIENT?

  • 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?

  • System out on Dual Monitor systems

    Hi,
    I am trying to write an application running on single processor, but dual monitor facility. So differnet monitor must get differnet display from same process.
    May I know how can I capture the monitor standard output. I know we have System.out that is set to standard monitor, in this case I "think" it will consider the first monitor has standard output. So, how can I capture actual output stream to each monitor so that I can set the system out property to which ever monitor I wish.
    Thanks
    HKG...

    I don't understand. System.out and System.err write to the standard out and err streams. When running Java in a command window under a GUI environment like Windows, Mac OS or Unix or Linux with X-based graphical displays, these streams will be default be displayed in the shell window that started the program. This window will be on what every display you placed it, the Java program has no control.
    If the Java program is a GUI (AWT, Swing or SWT), then System.out and System.err output still goes (by default) to whatever shell window started the program or into the bit bucket if no shell windows as associated with starting the program.

Maybe you are looking for

  • Is it possible to connect an old cinema display (ADC) to an Imac (2012)?

    Hello, I want to add a second screen to my Imac and I found a Cinema Display (ADC). I went to see the screen and i connect it to my Macbook to test if it works. The guy who sold the screen had an ADC to DVI adapter and I bought an DVI to thunderbolt

  • Changes to master nested sequence not updating in new sequence

    Good morning - I have spent the past half hour or so searching the forum for this topic but have not found the answer. If the answer exists elsewhere, please point me in that direction; otherwise, here goes: I created a nested sequence by simply drag

  • Phone and Tablet versions are too small

    When using a phone or tablet to view my website www.elrocco.com.au the pages are too small. The desktop version is fine. I use GoDaddy for domain management and forward to elrocco.businesscatalyst.com When I use the url elrocco.businesscatalyst.com d

  • Help! - need to create/list groups in OS 10.5.2 unix

    I need to create some groups in order to install Oracle on my 10.5.2 MAC. 10.3.6 MAC had nireport and nicl to list and create groups. Unfortunately even tho I can get man pages for these commands, the commands themselves no longer exist. When I poste

  • Invalid change to class error when deploying EJB

    We have EJBs that were built by Webgain Visual Cafe and successfully deploy to WLS 5.1. We then use the WLE EJB Deployer Tool to build WLE container classes and deploy the same EJBs in WLE 5.1. One EJB does not deploy in WLE. The ULOG error message i