Getting output from StreamRedirectThread.java

Hi,
For the purpose of my work, I am trying to store the output that is produced by StreamRedirectThread.java into a vector as shown in the code below. When I try to print out that vector the output is not as the same as it is printed in the StreamRedirectThread.java program. For example if the output form the program prints out the numbers form 0 to 5, the vector output is doubled in size and prints:
index = 0 content=0
index = 1 content=
index = 2 content=1
index = 3 content=
index = 4 content=2
index = 5 content=
index = 6 content=3
index = 7 content=
index = 8 content=4
index = 9 content=
index = 10 content=5
index = 11 content=
Can anybody advice me what to do about it. I tried but couldn't fix it. The code of StreamRedirectThread.java is as
import java.io.*;*
*import java.util.*;
import com.sun.jdi.*;*
*import com.sun.jdi.request.*;
import com.sun.jdi.event.*;*
*import com.sun.jdi.connect.*;
class StreamRedirectThread extends Thread {
private final Reader in;
private final Writer out;
private static Vector outvector = new Vector(0); // victor of objects that contains output result
private static final int BUFFER_SIZE = 2048;
* Set up.
* @param name Name of the thread
* @param in Stream to copy from
* @param out Stream to copy to
StreamRedirectThread(String name, InputStream in, OutputStream out) {
super(name);
this.in = new InputStreamReader(in);
this.out = new OutputStreamWriter(out);
setPriority(Thread.MAX_PRIORITY-1);
public void run() {
try {
char[] cbuf = new char[BUFFER_SIZE];
int count;
while ((count = in.read(cbuf, 0, BUFFER_SIZE)) >= 0) {
//out.write(cbuf,0,count);
String s = new String(cbuf,0,count);
if (!(s.equals(null)))
TemplateApp.vv.addElement(s);
outvector.addElement(s); out.write(s);
out.flush();
} catch(IOException exc) {
System.err.println("Child I/O Transfer - " + exc);
public synchronized static Vector getOutVector()
return outvector ;
}Thanks a lot for help

The problem was with endline stored in the vector. I did the follwing and it worked for me.
String separator = System.getProperty("line.separator");
  while ((count = in.read(cbuf, 0, BUFFER_SIZE)) >= 0) {
             if ( count == 0 ) {
                continue;
             String s = new String(cbuf,0,count);
             out.write(s);
             out.flush();
             s = s.replace(separator, "");
             if (s.length() !=0 )
                        outvector.addElement(s);
       }

Similar Messages

  • Getting output from a process

    hi friends and gurus!
    can somebody give me actuall working code to get the
    output from a process let's say Process p=Runtime.exec("cmd c/ dir c:"); in windows,
    and stores the output in a textfile let's say out.txt.
    please give me the java code and not hints!
    any effort to help me will be highly appreciated.
    Thanx in advance!
    sparya.

    import java.io.File;
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.FileNotFoundException;
    class read{
    public static void main(String[] args){
    String data=""
      try{
       BufferedReader reader=new BufferedReader(new FileReader(new File(args[0])));
       while((data=reader.readLine())!=null){
        System.out.println(data);
      catch(FileNotFoundException fnfe){
       System.out.println("cant find file "+args[0]);
      catch(IOException ioe){
       System.out.println("cant read file "+args[0]);
    }to use type java read filename (including path if you need it)
    hint, type java read read.java (cool, its nearly a palindrome)

  • Transactional file output from a Java Stored Procedure invoked by trigger.

    I need to write information to a file from a Java Stored
    Procedure which is called from an insert trigger. This works OK
    except for the condition when a rollback is performed - the file
    is updated anyway.
    I need the Java Stored Procedure file output to be part of the
    transaction - performed on commit and skipped on rollback. Is
    there any way the Java Stored Procedure can be aware of the
    state of the transaction?

    i am Still facing the following problem:
    if i pass a parameter like :
    rm -f /test/menu.ksh
    then the required output is that the menu.ksh file gets deleted.
    but when i pass this command:
    ./test/menu.ksh
    It is supposed to execute the specified script but it does not.
    I have tried multiple things like giving chmod 777 rights to the following file and changing the command to /test/menu.ksh but nothing happens
    Can you kindly tell me what can the problem be. Is there any execution rights issue: i am executing these scripts from pl sql developer.
    You can find both the procedure and java method which is being called below
    ==========================================================================================
    create or replace procedure TEST_DISPLAY(filename in varchar2, result out varchar2, error out varchar2) is
    command varchar2(100);
    vRetChar varchar2(100);
    begin
    command := filename ;
    prc_host(command, vRetChar);
    result := vRetChar;
    dbms_output.put_line(result);
    Exception
    when No_Data_Found Then
    error := 'Command is not Found';
    dbms_output.put_line('Failure');
    return;
    end TEST_DISPLAY;
    ======================================================================
    create or replace and compile java source named host as
    import java.io.*;
    import java.lang.Runtime;
    import java.lang.Process;
    import java.io.IOException;
    import java.lang.InterruptedException;
    public class Host {
    public static void executeCommand(String command,String[] outString) {
    String RetVal;
    try {
    String[] finalCommand;
    final Process pr = Runtime.getRuntime().exec(command);
    // Capture output from STDERR...
    }

  • Get output from dos window to jtextarea/textarea

    hi
    i am executing the following lines of code:
    1)Runtime r=Runtime.getRuntime();
    Process p=r.exec("javac <filename.java>");
    when executing this there is no exception fired but i am not being able
    to get the output from the ods console to a textarea
    or for that matter i donot get any output anywhere
    2)if i change it to
    Process p=r.exec("java <filename");
    similar thing happens i.e no output
    can anyone plz help
    thanx.

    Sorry, this < was the wong way around
    Process p=r.exec("java filename >test.txt")
    Then read in data from test.txt, something like this should do it :))   public String getTextFile(String text) throws Exception{
          int reader = 0;
          text = "";
          FileReader in = new FileReader("test.txt");
             do {
                reader = in.read();
                text += (char)reader;
             }  while (reader != -1);
          in.close();
          return text;

  • Get days from the java.util.date class

    Does anyone know how to get the days from the java.util.date
    class. I'm trying to subtract two dates to get the total days between
    the two dates. Any help would be appriciated
    Rob

    If you use the getTime() method, you get the date as a number of milliseconds since a predefined time. You can do arithmetic on that number, such as subtracting two of them to get the number of milliseconds between two Dates, and so on.

  • Error Getting Output From ICloudTask

    I went through the Azure Batch Tutorial for .NET and am having issues with getting the output from the ICloudTask. After waiting for the tasks to complete I have the coded below:
    foreach (ICloudTask task in listjob.ListTasks())
    string taskFileContent = task.GetTaskFile(Constants.StandardOutFileName).ReadAsString();
    Console.WriteLine("Task " + task.Name + " says:\n" + taskFileContent);
    It throws a System.AggregateException on task.GetTaskFile with an inner exception of:
    {"The remote server returned an error: (404) Not Found."}
    I did some research but haven't been able to determine why I am getting this error?

    I see in the sample that the second use of TaskStateMonitor (TSM) does not check for timeout...  We will add this and you might want too as well.  
    If the TSM times out you might want to confirm the pool has VMs and that they reach TVMState.Idle (i.e.: are available to run tasks).
    You do not mention the exact task state you see but it is possible for a task to be in the TaskState.Completed state and still not have a stdout.txt file.
    You could list the files with ICloudTask.ListTaskFiles(recursive: true) to see what files are actually there.
    Also you can check the exit code (ICloudTask.TaskExecutionInformation.ExitCode) and/or the the TaskSchedulingError (ICloudTask.TaskExecutionInformation.SchedulingErrro) to see if the task ran correctly.
    daryl
    ps: don't forget to ToString() the inner BatchException.  I posted to the forum earlier on this and there are data in the exception that can tell you more than "not found"... 

  • Not getting outputs from JavaScript Patch in QC2

    The JavaScript Patch no longer generates outputs from outputs[n]. The outputting of data just stopped.
    An example output generator (no other instructions in the JavaScript patch):
    outputs[0] = "string";
    was sent to an Image With String patch and then to a Billboard patch (the only existing patches). No text appeared in the viewer. When in Editor, the cursor placed over Output #0 shows only:
    Type Virtual
    with no value. The input string into Image With String shows "".
    When disconnecting the JavaScript patch from the Image With String patch and I entered "help", the text help appeared in the viewer.
    I reinstalled Quartz Composer and there was no change. Anyone have any idea what is going on?

    What I've learned: the Tascam 122L has known issues when working with Leopard. Back in the store, I plugged another external card (Presonus Audiobox USB), which immediately worked with the Mac as though they were friends since birth.
    I am rapidly warming to Mainstage.

  • When you want to get away from programming Java...

    Wow, what week, Just curious to know, what do others do to wind-down or get away from programming? PC Games, reading, outdoor stuff? Myself, I am interested in purchasing either NeverWinter Nights or WarCraft III as another way to make "computers fun" again...
    (Plus, any PC Game suggestions are welcomed.)
    Thanks for reading this post!
    --Todd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    If you're into RPG's, my favorite is Wizardry 8. Great plot, characters, and world. Dated graphics. I do like having a full party and 1st person perspective. I've been playing a lot of Grand Theft Auto (Vice City)--sort of a first person driver/shooter with RPG elements.

  • Displaying the output from a java class executed from W/I another class

    I have compiled a java class, but I have run into a problem executing the class. I have read the posts and still have not solved the solution. I have tried to get the output of the Process by using "proc.getOutputStream().toString()", however it displays it in binary (ex. java.io.BufferOutputStream@48eb2067). If anyone can provide any assistance I would greatly appreciate it. Or if you could tell me if I'm on the right track or not. Thanks ALL. Here is a code segment:
    int truncStart = s.indexOf(".java");
                   s = s.substring(0,truncStart);
                   String[] command2 = {"java","c:/"+s};
                   try
                   //JOptionPane.showMessageDialog(null,"Exec. File "+s, "Exec. File : ",JOptionPane.ERROR_MESSAGE);
                   proc = Runtime.getRuntime().exec(command2);
                   JOptionPane.showMessageDialog(null,"Output: "+proc.getOutputStream().toString(),"Output"
    ,JOptionPane.ERROR_MESSAGE);
                   }

    You have to read the stream, like:
    InputStream stream = proc.getOutputStream();
    // now use methods on stream, such as read() to read the characters/lines - or wrap it in another line-friendly stream - see the java.io.* classes - keep reading until you get an end-of-stream indicator, depending on the API you end up using.

  • Getting output from an OS command from an ABAP program

    Hi Folks!
    I have a requirement, is it possible to call an operating system command, and also get its output back to the ABAP program that has called it?
    For example, from an ABAP program calling the "dir" command from Windows and getting back (as a string) the directory listing to the ABAP program?
    Thanx in advance!
    Juan.

    This is will help you
    << Moderator message - links removed >>
    Please do not post a list of links. This simply encourages laziness. The OP could have found these with a little work.
    Edited by: Rob Burbank on Dec 13, 2010 9:19 AM

  • Giving input to running EXE & getting output from it

    Hi there,
    I want to invoke an EXE file using runtime.exec() & also want to give some input to it when it's in running state & also want to trace the output of that EXE.
    I tried it using PipedStream but failed to do this,
    please suggest something.
    Thanks In Advance,
    parag

    Here is my code.......
    //Pipe Writer class
    import java.io.*;
    public class Pipe_Writer extends Thread {
         PipedWriter pWriter = new PipedWriter();
         public Pipe_Writer() {}
         public PipedWriter getPipedWriter() {
              return pWriter;
         public void run() {
              Process p = null;
              try {
                   p = Runtime.getRuntime().exec("cmd");
              } catch (IOException e) {
                   e.printStackTrace();
              BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
              BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
              BufferedReader reader2 = new BufferedReader(new InputStreamReader(System.in));
              String line;
              String rd = "";          
              try {
                   rd = reader2.readLine();
                   System.out.println(rd);               
              } catch (IOException e1) {
                   e1.printStackTrace();
              try {
                   // writer.write("dir\n"); //writing to process
                   writer.write(rd + "\n");
                   writer.flush();          
                   while ((line = reader.readLine()) != null) {
                             System.out.println(line);
                             pWriter.write(line);  //writing to pipe
              } catch (IOException e) {
                   e.printStackTrace();
    }// Pipe reader class
    public class Pipe_Reader extends Thread{
         PipedReader pReader;
         public Pipe_Reader(Pipe_Writer writer)throws IOException{
              pReader = new PipedReader(writer.getPipedWriter());
         public void run(){
              try {               
                   while(true){
                        System.out.println((char)pReader.read());  //Reading from pipe
              } catch (Exception e) {
                   e.printStackTrace();
    }// main method
    public static void main(String[] args)throws IOException {
              Pipe_Writer writer = new Pipe_Writer();
              Pipe_Reader reader = new Pipe_Reader(writer);
              writer.start();
              reader.start();
         }

  • Getting output from a C programme

    Hi
    I am trying to execute a C programme (.o file) on Solaris and get its output .
    The C programme is a simple function which returns 0 or more then zero after executing some logic .
    I tried to use Runtime.exec() method but was not able to get any out put from the function , where as I did same in a perl script and was able to get the output .
    I have even tried to get error stream , input stream but I always get -1 as a return value .
    Following is my program
    Runtime rt = Runtime.getRuntime();
    String[] arg =new String[]{"program","arg1","arg2"};
    Process p =rt.exec(arg);
    BufferedInputStream buf = new     BufferedInputStream(p.getErrorStream());
    int data=buf.read();
    System.out.println("date is "+data);
    BufferedInputStream buf1 = new     BufferedInputStream(p.getInputStream());
         while((data=buf1.read())!= -1)
              System.out.println("data input is "+data);
    arg1 and arg2 are 2 arguments that the program needs . It always returns a value with might be 0 or non zero.
    I know I can try to use JNI , but i beleive using Process is a simple solution (if it works)
    Thanks

    .o files are usually no executables but object files. They need to be linked (with an object including the main funtion) to yield an executable.
    Shared objects are usually called *.so.

  • Strange output from my java file

    Hi all,
    I made a post not long too long ago about some issues i was having. However since then i have not been able to come online or continue much with my work. I've just starting working on it again and after fixing the errors and implementing a little more code i had an unexpected output.
    Compiles fine, no errors Just a warning about not checking my vectors etc. But when i run the class file it does not display the grid like i thought it would.
    My code is below, but first is what i get when i run the class file after compiling.
    [[I@1fc4bec
    import java.util.Arrays.*;
    import java.util.Random.*;
    import java.lang.*;
    import java.util.*;
    public class SnakeGame
                //Fields
               final int
                         GRIDSIZEX        = 31,   //Stores the horizontal size of the grid
                         GRIDSIZEY       = 31,   //Stores the vertical size of the grid
                         SNAKESTARTX      = 15,   //Snakes horizontal start possition
                         SNAKESTARTY      = 15,   //Snakes Vertical start position
                         SNAKEBODYOFFSETX = -1,   //Does the body go left (neg) or right (pos) at start
                         SNAKEBODYOFFSETY = 0,   //Does the body go up (neg) or down (pos) at start
                         BLANK            = 0,   //Flag for blank space
                         WALL             = 1,   //Flag for wall
                         SNAKEHEAD        = 2,   //Flag for snakeshead
                         SNAKEBODY        = 3,   //Flag for snakesbody
                         FOOD             = 4,   //Flag for food
                         FRUIT            = 5,   //Flag for fruit
                         SNAKEATER        = 6;   //Flag for snakeater
                 int[][] boardGrid;  //the playing field
         public static void main(String[] args)
              SnakeGame snakeGame = new SnakeGame();
              snakeGame.initBoard();
              Vector Snake = new Vector();
              String h1 = new String("+");
              Snake.add(h1);
              String b1 = new String("~");
              Snake.add(b1);
              int x;
              int y;
         public void wall()
              char TOP_BOTTOM = '_';
              char LEFT_RIGHT = '|';
         public void food()
              char F = 'F';
              Object food = new Object();
         public static Object grid()
              Object Grid = new Object[31][31];
              Random x = new Random(31);
              Random y = new Random(31);
              return grid();
                   * This method sets up the playing field by placing the walls around the edge, snake at start,
                   * and the blanks.
                   private void initBoard()
                                  boardGrid = new int [GRIDSIZEX][GRIDSIZEY];
                              for(int row = 0; row < boardGrid.length; row++)
                                      for(int col = 0; col < boardGrid[0].length; col++)
                                                      //Insert a wall around edge
                                                      if (row == 0 || row == (boardGrid.length -1) || col == 0 || col == (boardGrid[0].length -1))
                                                             boardGrid[row][col] = WALL;
                                                 //Insert the snakes head
                                                 else if (row == SNAKESTARTX && col == SNAKESTARTY)
                                                         boardGrid[row][col] = SNAKEHEAD;
                                                 //Insert the snakes one body peice
                                                 else if (row == SNAKESTARTX + SNAKEBODYOFFSETX && col == SNAKESTARTY + SNAKEBODYOFFSETY)
                                                              boardGrid[row][col] = SNAKEBODY;
                                  else if (row == FOOD && col == FOOD)
                                       boardGrid[row][col] = FOOD;
                                                      //Make all the rest blanks
                                                 else
                                                    boardGrid[row][col] = BLANK;
                   System.out.println(boardGrid);
    }

    When you want to print an array then you can't just do
    System.out.println(someArray);This implicitly calls .toString() on the array which produces the result that you saw (= something that isn't very useful).
    You could write
    System.out.println(Arrays.deepToString(someArray));(after inporting java.util.Arrays).

  • Test.jsp not able to display the output from the java code.

    when i try to invoke http://localhost/papz/test.jsp
    I dont see anything. The page is blank. And there are no error messages in any log files. When i click on view source in IE i get to see the entire source code, including the jave code.
    <html>
    <head>
    <title>Test</title>
    <body>
    <%
    out.println("Hello World");
    %>
    asdfasdfasdf
    </body>
    </html>
    i added in the asdfasdf to see whehter it will be printed or not... It does print that stuff out.
    when i try to invoke the login.jsp page, i get the dialog box "save this file to disk"
    Any clues whats going on...?
    I followed the instructions...over and over again... but it doesnt seem to help.
    win nt 4.0
    apache 1.3.12
    jserv 1.1.1
    Pls help. Thanks

    Hi,
    Have you solved your problem?
    I4m trying to do the same, but I installed portal 30, then portal to go, and when I try to run test.jsp I get the following error:
    Request URI:/papz/test.jsp
    Exception:
    java.lang.NoSuchMethodError: oracle.jsp.util.JspUtil: method
    stripTarget(Ljava/lang/String;C)Ljava/lang/String; not found
    Thanks
    Pablo Lopera
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by NewBie:
    when i try to invoke http://localhost/papz/test.jsp
    I dont see anything. The page is blank. And there are no error messages in any log files. When i click on view source in IE i get to see the entire source code, including the jave code.
    <html>
    <head>
    <title>Test</title>
    <body>
    <%
    out.println("Hello World");
    %>
    asdfasdfasdf
    </body>
    </html>
    i added in the asdfasdf to see whehter it will be printed or not... It does print that stuff out.
    when i try to invoke the login.jsp page, i get the dialog box "save this file to disk"
    Any clues whats going on...?
    I followed the instructions...over and over again... but it doesnt seem to help.
    win nt 4.0
    apache 1.3.12
    jserv 1.1.1
    Pls help. Thanks<HR></BLOCKQUOTE>
    null

  • Getting output from my MBP to LCD TV

    Read any postings in this forum but could not find an answer. I have Apple's mini displayport, a DVi to HDMI cable and the appropriate audio cables.
    After connecting the MBP to the LCD TV I can see the desktop on the TV**. However when I closed the lid the TV goes black. With the lid open I run front row and it work on the MBP screen and on the TV I only get the same desktop image**
    What am I doing wrong?
    ** By the way the desktop picture in my MBP doesn't show. What it shows on the TV is the apple desktop purple "galaxy" image. Interesting!

    eew and Network 23,
    Thanks for adding to my post. It is very clear now. One of the problems I had is that I didn't realize that in System Preference>Displays, the menu changes a bit if you have the monitor connected or not.
    Two more questions,
    1) Based on your suggestions I prefer the extended desktop mode to preserve higher output resolution. I guess that when you have Mirroring off, it automatically means that you have the Extended Desktop option on, right?
    2) I cannot get the whole thing to work when I close my MBP. The TV goes black. I have an external mouse and keyboard (both bluetooh). I played with the "Arrangement" setting but nothing. What am I doing wrong.
    Thanks in advance.

Maybe you are looking for