Current dir + Runtime.getRuntime() ???

Hello all,
I am working on a programming that need execute other exe file. The problem is I have to put that exe file in Window system file directory, then I can execute this exe file. However, what I want is not puting that exe file in Window system, just put that exe file in current working directory. and exe it.
thanks
here is some codes, but does not work as I want
import java.lang.Runtime;
class TestVB
{   public static void main(String[] args)
{  Runtime run = Runtime.getRuntime();
try{  Process a = run.exec("a.exe"null, null);
//or
String path = System.getProperty("user.dir")+System.getProperty("file.separator")+"a.exe"];
     Process a = run.exec(path,null, null);
catch(Exception es)
{ System.out.println(es);

Go through this:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
it shows the best way to use Runtime.exec() function along with its pitfalls.
i hope it helps!

Similar Messages

  • Runtime.getRuntime().exec works on windows failed on linux!

    Hi,
    I'm trying to execute a linux command from java 1.4.2 using Runtime.getRuntime().exec(). The linux command produces output and write to a file in my home dir. The command runs interactively in the shell and also run on windows.
    The command is actually a mozilla pk12util. My java code to run this pk12util works on windows, but not on linux (fedora). When I print out the command I'm trying to run in java, I can run it interactively in bash shell.
    Method below is where the problem seems to be:
    public void writeCert() {
    // Declaring variables
    System.out.println("Entering writeCert method");
    String command = null;
    certFile = new File(credFileName);
    // building the command for either Linux or Windows
    if (System.getProperty("os.name").equals("Linux")) {
    command = linuxPathPrefix + File.separator + "pk12util -o "
    + credFileName + " -n \"" + nickName + "\" -d "
    + dbDirectory + " -K " + slotpw + " -w " + slotpw + " -W "
    + pk12pw;
    System.out.println("System type is linux.");
    System.out.println("Command is: " + command);
    if (System.getProperty("os.name").indexOf("Windows") != -1) {
    // command = pk12utilLoc + File.separator + "pk12util -o
    // "+credFileName+" -n "\"+nickname+\"" -d \""+dbDirectory+"\" -K
    // "+pk12pw+" -w "+pk12pw+" -W "+pk12pw;
    command = pk12utilLoc + File.separator + "pk12util.exe -o "
    + credFileName + " -n \"" + nickName + "\" -d "
    + dbDirectory + " -K " + slotpw + " -w " + slotpw + " -W "
    + pk12pw;
    System.out.println("System type is windows.");
    System.out.println("Command is: " + command);
    // If the system is neither Linux or Windows, throw exception
    if (command == null) {
    System.out.println("command equals null");
    try {
    throw new Exception("Can't identify OS");
    } catch (Exception e) {
    System.out.println(e.getMessage());
    e.printStackTrace();
    // Having built the command, running it with Runtime.exec
    File f = new File(credFileName);
    // setting up process, getting readers and writers
    Process extraction = null;
    BufferedOutputStream writeCred = null;
    // executing command - note -o option does not create output
    // file, or write anything to it, for Linux
    try {
    extraction = Runtime.getRuntime().exec(command);
    } catch (IOException e) {
    System.out.println(e.getMessage());
    e.printStackTrace();
    // Dealing with the the output of the command; think -o
    // option in command should just write the credential but dealing with output anyway
    BufferedWriter CredentialOut = null;
    OutputStream line;
    try {
    CredentialOut = new BufferedWriter (
    new OutputStreamWriter(
    new FileOutputStream(credFileName)));
    catch (FileNotFoundException e) {
    System.out.println(e.getMessage());
    e.printStackTrace();
    // writing out the output; currently having problems because I am trying to run
    }

    My error is due to the nickname "-n <nickname" parameter error. I think the problem is having a double quotes around my nickname, but if I take out the double quotes around my nickname "Jana Test's ID" won't work either because there are spaces between the String. Error below:
    Command is: /usr/bin/pk12util -o jtest.p12 -n "Jana Test's Development ID" -d /home/jnguyen/.mozilla/firefox/zdpsq44v.default -K test123 -w test123 -W test123
    Read from standard outputStreamjava.io.PrintStream@19821f
    Read from error stream: "pk12util: find user certs from nickname failed: security library: bad database."
    null
    java.lang.NullPointerException
    at ExtractCert.writeCert(ExtractCert.java:260)
    at ExtractCert.main(ExtractCert.java:302)
    Code is:
    private String nickName = null;
    private void setNickname(String nicknameIn) {
    nickName = nicknameIn;
    // building the command for either Linux or Windows
    if (System.getProperty("os.name").equals("Linux")) {
    command = linuxPathPrefix + File.separator + "pk12util -o " + credFileName + " -n \"" + nickName + "\" -d " + dbDirectory + " -K " + slotpw + " -w " + slotpw + " -W " + pk12pw;
    System.out.println("System type is linux.");
    System.out.println("Command is: " + command);
    extraction = Runtime.getRuntime().exec(command);
    BufferedReader br = new BufferedReader(
    new
    InputStreamReader(extraction.getErrorStream()));
    PrintStream p = new PrintStream(extraction.getOutputStream());
    System.out.println("Read from standard outputStream" + p);

  • Running commands from the Command Prompt -  Runtime.getRuntime().exec()

    Hi there,
    I'm already able to run several commands in the command prompt.
    But my problem is that I need all the commands that I run share the same context.
    If, for example, I run "cmd /c set HOME=C:" (1st command), I want to be able to access that variable the next time, so that later when I run "dir %home%" it shows the directories in c: (This is just a example this is not what I really want to do...)
    I used code posted in a newsgroup (don't remember which)
    This is the code I use to execute commands:
         private int execute(String command)
         int exitVal = 0;
    try
    String nomeOS = System.getProperty("os.name" );
    String[] cmd = new String[3];
    if( nomeOS.equals( "Windows NT" ) || nomeOS.equals("Windows 2000") )
    cmd[0]="cmd.exe";
    cmd[1]="/c";
    cmd[2]=command;
    else if( nomeOS.equals( "Windows 95" ) )
    cmd[0]="command.com";
    cmd[1]="/c";
    cmd[2]=command;
    if (rt==null)
         rt = Runtime.getRuntime();
              Process proc = rt.exec(cmd);
              CommandStream erro = null;
              // erros?
              if (proc.getErrorStream()!=null)
                   erro = new CommandStream(proc.getErrorStream());
                   erro.start();
    // output?
    CommandStream output = new
    CommandStream(proc.getInputStream());
    // arranque
    output.start();
    // erros???
    exitVal = proc.waitFor();
         } catch (IOException e)
                   System.out.println("Exce !!!" );
                   e.printStackTrace();
         catch (InterruptedException ie)
                   System.out.println("Ocorreu uma excep��o !!!" );
                   ie.printStackTrace();
    return exitVal;      

    My problem is bigger than setting a few parameters,
    I'm doing a GUI to a CVS client and the problem is that some commands of CVS only work if you're in the right directory, or if you're authenticated, and all of this is easily done doing a series of execution:
    In a command prompt opened I would:
    set cvsroot=:pserver:lpinho@w2palf38:/project
    cvs -d :pserver:lpinho:xxxxx@w2palf38:/project login
    mkdir temp_my_proj
    cd temp_my_proj
    cvs checkout my_projectAll this would make what I wanted...
    And there's another thing, when I set the envp, I get some errors like "cvs.exe is not recognized as an internal or external command" (the path went bye bye) and if I set the path (envp[0]="path=c:\cvsnt"), I'm able to run cvs but I get a crazy error "No such host is known" (I run exactly the same command in the command prompt and it works...)
    Do you know any way of getting the current environment, and pass it as the envp parameter?
    Thank You
    Luis Pinho

  • How to execute an application in Solaris using Runtime.getRuntime.exec() ?

    I am currently doing a project which requires the execution of Solaris applications through the use of Java Servlet with this Runtime method - Runtime.getRuntime.exec()
    This means that if the client PC tries to access the servlet in the server PC, an application is supposed to be executed and launched on the server PC itself. Actually, the servlet part is not an issue as the main problem is the executing of applications in different platforms which is a big headache.
    When I tried running this program on a Windows 2000 machine, it works perfectly fine. However, when I tried it on a Solaris machine, nothing happens. And I mean nothing... no errors, no nothing. I really don't know what's wrong.
    Here's the code.
    public void doPost(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException
         response.setContentType("text/html");
         PrintWriter out = response.getWriter();
              Process process;                                                       Runtime runtime = Runtime.getRuntime();
              String com= "sh /opt/home/acrobat/";
              String program = request.getParameter("program");
              try
                        process = runtime.exec(com);
              catch (Exception e)
                   out.println(e);
    It works under Windows when com = "c:\winnt\system32\notepad.exe"
    When under Solaris, I have tried everything possible. For example, the launching of the application acrobat.
    com = "/opt/home/acrobat"
    com = "sh /opt/home/acrobat"I have also tried reading in the process and then printing it out. It doesn't work either. It only works when excuting commands like 'ls'
    BufferedReader read = new BufferedReader(new InputStreamReader(process.getInputStream()));Why is it such a breeze to execute prgrams under Windows while there are so many problems under Solaris.
    Can some experts please please PLEASE point out the errors and give me some advice and help to make this program work under Solaris! Please... I really need to do this!!
    My email address - [email protected]
    I appreciate it.
    By the way, I'm coding and compiling in a Windows 2000 machine before ftp'ing the .class file to the Solaris server machine to run.

    it is possible that you are trying to run a program that is going to display a window on an X server, but you have not specified a display. You specifiy a display by setting the DISPLAY environment variable eg.
    setenv DISPLAY 10.0.0.1:0
    To check that runtime.exec is working you should try to run a program that does not reqire access to an X Server. Try something like
    cmd = "sh -c 'ls -l > ~/testlist.lst'";
    alternatively try this
    cmd = "sh -c 'export DISPLAY=127.0.0.1:0;xterm '"
    you will also need to permit access to the X server using the xhost + command

  • Output of Process p=Runtime.getRuntime().exec("java filename

    Runtime r=Runtime.getRuntime();
    Process p=r.exec("java <filename>");
    on implementing this code no exception is fired
    nor there is any output on console window rather the console window
    doesn't open.
    can anyone help
    2nd question:
    Runtime r=Runtime.getRuntime();
    Process p=r.exec("cmd.exe dir");
    on executing it in windows xp it shows cannot open 16-bit windows application

    Runtime r=Runtime.getRuntime();
    Process p=r.exec("java <filename>");
    InputStream is = p.getInputStream();The standard output stream of the programm, you are starting, is the input stream of your process.

  • Runtime.getruntime.exec() getOutputStream()

    Hi,
    can anyone tell me what this is used for?
    i though i maybe could use it in this example
    exec(cmd /c start)
    out.write("dir".getBytes());
    but that doesn't seem to work?
    also does anyone know like if i want to start a cmd and want to keep that open and do multiple commands like first cd then dir
    i thought u could with the ouputstream, but that isn't right? or am i wrong?
    thanks in advance

    You need something like
           String[] command =
                "cmd",
            Process p = Runtime.getRuntime().exec(command);
            new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
            new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
            PrintWriter stdin = new PrintWriter(p.getOutputStream());
            stdin.println("dir c:\\ /A /Q");
            // write any other commands you want here
            stdin.close();
            int returnCode = p.waitFor();
            System.out.println("Return code = " + returnCode);where SyncPipe is a runnable in which the run() method copies the content of the InputStream to the OutputStream. You can use StreamGobbler instead.
    Note - commands sent to the stdin of cmd.exe need to be terminated by a new line. When you have finished all input you should close stdin.
    Note 1 - since the string "dir c:\\ /A /Q") is interpreted by cmd.exe you MUST use the \ char as a file separator.

  • Runtime.getRuntime().exec() problem while getting Mozilla version.

    Hi all,
    I've trying to get the current mozilla version in Java side using
    Runtime.getRuntime().exec(). The sample code is as below.
    I've tested two cases using exec(), as case# 1 and case# 2.
    The result is after the code.
    try
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(new String[] {"mozilla", "-remote"}); //case# 1
    //Process proc = rt.exec(new String[] {"mozilla", "-version"}); //case# 2
    InputStream stderr = proc.getErrorStream();
    InputStreamReader isr = new InputStreamReader(stderr);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    System.out.println("<ERROR>");
    while ( (line = br.readLine()) != null)
    System.out.println(line);
    System.out.println("</ERROR>");
    int exitVal = proc.waitFor();
    System.out.println("Process exitValue: " + exitVal);
    } catch (Throwable t) {
    t.printStackTrace();
    // execute "mozilla -remote"(case# 1)
    $ java TestExec
    <ERROR>
    -remote requires an argument
    </ERROR>
    Process exitValue: 1
    // execute "mozilla -version"(case# 2)
    $ java TestExec
    <ERROR>
    </ERROR>
    Process exitValue: 0
    I'm just surprised that why case# 2 couldn't get the returned version string as case #1 ? Since there will be version string be returned from command line:
    $ mozilla -version
    Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.0.1) Gecko/20020830, build 2002083014
    Could anybody explain the problem or give any solution ?
    Thanks.
    -George.

    Hi all,
    One more question here.
    While I use Runtime.getRuntime().exec() to execute some commands,
    the commands may fail for some reason. Generally, they will return with the exit
    value set to 1 or others. But sometime, before waitFor() exits, there is a popped up
    dialog giving some info, and only after I click the "OK" button, it dispears, and
    waitFor() returns the exit value.
    So I'm not sure that could I suppress this popped up dialog, and make it run
    just like other commands ? I mean, just get the exit value by waitFor() without user
    interferance ?
    Thanks.
    -George.

  • Need help on changing directories with Runtime.getRuntime().exec() (shell)

    I want to create a perfect remote shell with Runtime.getRuntime(). I just can't get it to change directories. I want that if the remote user type "cd.." he changes the directory. At the moment, I can't get anything else than the "user.dir" directory.
    Is there anyway to send additionnal commands to cmd.exe after the Runtime.getRuntime().exec(). Because at the moment I'm running these commands:
    cmd[0] = "cmd.exe" ;
    cmd[1] = "/C" ;
    cmd[2] = commandString;
    After that I just wanna do stuff as if I really was at the computer and had a cmd.exe window open. I tried the output stream, I tried placing "&&" in front of the commandString(worked when I did it in cmd window), tried doing multiple Runtime.getRuntime().exec(). Starting to pull my hair out here.

    Because essentially I want this to be a remote shell.
    So I need it to accepts commands such as cd to change
    around the directory so the person can navigate the
    computer.
    I just managed to be able to do it in one command
    line. For example I would send "cd c:\downloads dir"
    to the server and it would work but I would really
    like to keep track of the working directory so the
    user wouldn't always have to change the directory.Then you don't Runtime.exec() once for each command the user types. You Runtime.exec() a shell once, and pass what the user types and the shell's responses via the in/out streams available from the Process class.

  • Need help with Runtime.getRuntime().exec

    If there is a better place to post please let me know. I need some help understanding what is going on and was hoping someone might be able to provide some information. I would like to use Runtime.getRuntime().exec to copy a file in linux. Here is the code I am using:
    try {
    Process p = Runtime.getRuntime().exec("cp -v foo foo2");
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;
    while ((line = in.readLine()) != null) {
    System.out.println(line);
    } catch (IOException e) {
    e.printStackTrace();
    If I use cp, with the System.out.println(line) I can see that it has copied and of course when I check the command line indeed it has. My problem is that I really need to use the dd command, but I can't see the output that dd displays. It copies the file just fine but I need the output. If someone can provide some explaination or help I would really appreciate it. Thanks.

    By default, dd sends its output to stdout, so any status messages it has go to stderr. Use getErrorStream (double check the docs for the method name) just like you're currently using getInputSTream.

  • Runtime.getRuntime().exec() and waitFor on Windows

    Hi,
    I'm trying to execute a command on Windows 2000 using Runtime.getRuntime().exec(). After that I make a call to waitFor method of the returned process instance. The wait for call blocks and never releases. I'm trying to do simple things, like a call to "cmd /c dir", using commands that I know that work and do release after that. I need to wait for the command terminating to get the output just after that.
    Thanks in advance,
    Marcio Azevedo.

    It's too bad ignoring the streams couldn't be build into ProcessBuilder. Instead you could do it yourself and extend ProcessBuilder like:
    public class MyProcessBuilder extends ProcessBuilder {
      private boolean ignoreInputStream;
      public  MyProcessBuilder(List<String> command) {
         super(command);
      public  MyProcessBuilder(String... command) {
         super(command);
      public boolean ignoreInputStream() {
        return ignoreInputStream;
      public  ProcessBuilder ignoreInputStream(boolean ignoreInputStream) {
        this.ignoreInputStream= ignoreInputStream;
        return this;
      public Process start() {
        Process process = super.start();
        if (ignoreInputStream()) {
             new InputStreamIgnorer(process.getInputStream());
        return process;
      static class InputStreamIgnorer implements Runnable {
        java.io.InputStream in;
        InputStreamIgnorer(java.io.InputStream in) {
          this.in = in;
          new Thread(this,"InputStreamIgnorer Thread").start();
        public void run() {
          int ch;
          try {
            while((ch = in.read()) != -1) {
                //System.out.print(ch);
          } catch (java.io.IOException ex) {} //ignore
    }Then it could be simpled used like:
    new MyProcessBuilder("cmd","/c", "dir").redirectErrorStream(true).ignoreInputStream(true).start().waitFor();

  • Using Process Runtime.getRuntime().exec

    http://im1.shutterfly.com/procserv/47b4d633b3127cceb46774c84ee80000001610
    Here is a URL to a part of the current process I need to run. Actually there are 4 steps that preceed these but they are ran in order and must be done before these (that part is easy). Sorry it kinda chopped off the left side a little bit.
    My question is, can I do this entirely using Runtime.getRuntime().exec() commands or do I need to involve multi threading. The reason I am asking is because P13 cannot run until P8 and P9 completes, but that shouldn't stop the rest of the program from running.
    If I have something like
    Process P4 = Runtime.getRuntime().exec(P4);
    Process P5 = Runtime.getRuntime().exec(P2);
    // Some handling for the streams of these processes goes here
    P4.waitFor();
    P2.waitFor();
    if(P2.exitValue() != 0){
    Process P5 = Runtime.getRuntime().exec(P5);
    Process P6 = Runtime.getRuntime().exec(P6);
    // Some handling for the streams of these processes goes here
    Does that mean the whole program will stop and wait until P4 is done before even checking for P2? If P2 is finished would the program continue and run P5 and P6 even if P4 is still running or will it wait for P4 to complete also. P4 has nothing to do with P2?
    Also any advice ???

    P4 and P2 will both be running in parallel (or as much as your OS and hardware allows them to be). As soon as both are done, and regardless of which finishes first, whatever follows P2.waitFor() will execute.
    If you have multiple groups of processes, where the processes within a group must execute sequentially, but the groups themselves can run independently of each other, then you'll need to either use Java's threads, or wrap each group of sequential processes in a shell script or batch file the executes that group sequentially.
    If there are complex dependencies among the groups--that is, multiple groups must wait on the same process, or one group must wait for multiple other groups, then it might be easier to control the concurrency in Java.

  • Problems with Runtime.getRuntime().exe and getting output. Please Help me!!

    I'm creating a program that runs the followings programs written in C and compiled with gcc:
    ==========================The first C program====================================
    #include<stdio.h>
    void leia();
    main()
    int x = 20;
    int y = 2;
    printf( "Marcinho e Danny\n" );
    printf( "Te\n" );
    printf( "Vida\n" );
    printf( "Marciorja: %d.\n", x * y );
    ===============================================================================
    ==========================The second C program====================================
    #include<stdio.h>
    void leia();
    main()
    int x = 20;
    int y = 2;
    printf( "Marcinho e Danny\n" );
    printf( "Te\n" );
    printf( "Vida\n" );
    printf( "Marciorja: %d.\n", x * y );
    scanf( "%d", &x ); //This is the statement added to the latter C program.
    ===============================================================================
    I compiled this C program and generates the a.exe program. I have the following Java program:
    ==================================================================================
    import java.awt.Color;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.util.StringTokenizer;
    import javax.swing.JFrame;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.EditorKit;
    import javax.swing.text.MutableAttributeSet;
    import javax.swing.text.Style;
    import javax.swing.text.StyledDocument;
    import javax.swing.text.StyledEditorKit;
    public class Teste
    private BufferedWriter out;
    private BufferedReader in;
    private Style stylePrompt;
    private LeitorDeEntrada le;
    private String entrada = "";
    private AreaDeEdicao areaDeTexto;
    Process p = null;
    public Teste( AreaDeEdicao areaDeTexto )
    this.areaDeTexto = areaDeTexto;
    public void runCommand( String command ) throws IOException
    StringTokenizer strTokenizer = new StringTokenizer( command );
    String mainCommand = null;
    String argument = null;
    StyledDocument doc = areaDeTexto.getStyledDocument( );
    String[] prefix = new String[] { "cmd.exe", "/c", command };
    p = Runtime.getRuntime().exec( prefix, null, new File( System.getProperty( "user.dir" ) ) );
    in = new BufferedReader( new InputStreamReader( p.getInputStream( ) ) );
    out = new BufferedWriter( new OutputStreamWriter( p.getOutputStream( ) ) );
    out.flush();
    Thread t = new Thread( )
    public void run( )
    super.setName( "Marcio" );
    execute( );
    public void execute( )
    String c = null;
    try
    if( !in.ready( ) )
    try
    this.sleep( 1000 );
    catch( InterruptedException e2 )
    e2.printStackTrace( );
    System.out.println( "in.rea: " + in.ready( ) );
    c = in.readLine( );
    catch( IOException e )
    e.printStackTrace( );
    String str = "";
    while( c != null )
    str = c + "\n";
    try
    areaDeTexto.getDocument( ).insertString( areaDeTexto.getDocument( )
    .getLength( ),
    str, null );
    catch( BadLocationException e3 )
    e3.printStackTrace( );
    try
    c = in.readLine( );
    catch( IOException e2 )
    e2.printStackTrace( );
    areaDeTexto.setCaretPosition( areaDeTexto.getDocument( )
    .getLength( ) );
    try
    in.close( );
    catch( IOException e1 )
    e1.printStackTrace( );
    t.setDaemon( true );
    t.start( );
    le = new LeitorDeEntrada( );
    areaDeTexto.addKeyListener( le );
    public static void main( String[] args )
    JFrame janela = new JFrame( );
    AreaDeEdicao areaDeTexto = new AreaDeEdicao( new MyDocument( ) );
    areaDeTexto.setBackground( Color.black );
    areaDeTexto.setForeground( Color.GREEN );
    janela.getContentPane( ).add( areaDeTexto );
    Teste teste = new Teste( areaDeTexto );
    try
    teste.runCommand( "a.exe" );
    catch( IOException e )
    e.printStackTrace( );
    janela.setSize( 500, 300 );
    janela.setVisible( true );
    class LeitorDeEntrada extends KeyAdapter
    public void keyPressed( KeyEvent e )
    char c = e.getKeyChar( );
    System.out.println( "keyPressed" );
    try
    if( c == '\n' )
    areaDeTexto.getDocument().insertString( areaDeTexto.getDocument( )
    .getLength( ),
    c + "", null );
    out.write( c + "" );
    out.flush();
    catch( BadLocationException e2 )
    e2.printStackTrace( );
    } catch (IOException e2) {
    e2.printStackTrace();
    ==================================================================================
    This Java program is very simple. It runs the a.exe using the method Runtime.getRuntime().exec and gets input for a.exe from a JTextPane and shows the output in the same JTextPane.
    If my a.exe represents the binary code of the first C program the text in the JTextPane is the correct output of the a.exe. But, if my a.exe represents the binary code of the second C program, the JTextPane shows the messages ( "Marcinho e Danny\n", "Te\n", "Vida\n", "Marciorja: %d.\n") after I enter the value claimed by the scanf.
    I tested my Java program running programs that require input and all have the same behavior:.
    What can I need to do to solve this bug?
    I read other posts with the same problem and nobody answers what is the problem.
    I'LL pay 10 Duke dollars to the first that answers me.

    The second C program with the statement fflush( stdout ) produces the right output.
    #include<stdio.h>
    void leia();
    main()
    int x = 20;
    int y = 2;
    printf( "Marcinho e Danny\n" );
    printf( "Te\n" );
    printf( "Vida\n" );
    fflush( stdout ); //added statement.
    printf( "Marciorja: %d.\n", x * y );
    scanf( "%d", &x ); //This is the statement added to the latter C program.
    but what can I do to run C programs that doesn't flush the stdout?

  • Problem in Runtime.getRuntime().exec

    Hi,
    I am trying to start the tomcat server through a java application.Before starting the server,i need to run a batch file for setting up some classpaths.I am able to run the batch file and start the server,but its opening the 2 windows.How do i suppress it?
    One more problem is how do i stop the server?
    Code is:
    import java.io.*;
    public class Test
    public static void main(String args[]) {
    try {
         Process p = Runtime.getRuntime().exec("cmd /c start C:\\soap.bat");     
         p.destroy();
         Process p1 = Runtime.getRuntime().exec("cmd /c start C:\\jakarta-tomcat-3.2.1\\bin\\startup");
         //p.waitFor();     
         Thread.sleep(10000);
         p1.destroy();     
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
    bw.write("1");
    bw.flush();
    String line;
    while ((line = br.readLine()) != null) {
    System.out.println(line);
    br.close();
    bw.close();
    System.out.println(p.exitValue());
    catch(Exception e) {
    System.out.println(e);
    I need the help as early as possible.
    pls cc reply to:[email protected]
    Thanks
    Anitha

    Soln. to your first prob:
    1) To have the other DOS window closed, click on the extreme left-top corner of that window. In the menu that drops down ,select properties.In the properties window make sure the 'close on Exit' check Box is checked. Apply the changes.
    2) To stop the server u need to call the shutdown.bat file in the tomcat\bin dir. If u want to do this thru java then call the shutdown.bat file from your Runtime.exec() method. Same as u did for the startup file
    Hope this helps.

  • System.gc() Versus Runtime.getRunTime().gc

    Hi Guys,
    Which one is better System.gc or Runtime.getRuntime().gc()
    Because currently i am encounter out of memory Exception because i process a very large dataset..
    I test System.gc() on my system and it seems doesnt free up the memory while the Runtime.getRuntime().gc will free up the memory..
    I M just wondering why a lot of articles tell to use System.gc()
    Thanks.

    Hi
    System.gc doesnt really work fine for me..
    Here is my code
    import java.util.*;
    public class GCTest {
    final int NELEMS = 50000;
    public static Vector ve;
    public static Vector ve2;
    void eatMemory() {
         ve = new Vector();
    ve2= new Vector();
         for(long i=0;i<100000;i++)
                   ve.add("String");
                   String a="a";
                   if(i==90000)
         Runtime runtime = Runtime.getRuntime();
         //runtime.gc();
                        System.out.println ("Free memory after 90000 Record : " + runtime.freeMemory() );
    public static void main (String[] args) {
    GCTest gct = new GCTest();
    // Step 1: get a Runtime object
    Runtime r = Runtime.getRuntime();
    // Step 2: determine the current amount of free memory
    long freeMem = r.freeMemory();
    System.out.println("free memory before creating array: " + freeMem);
    // Step 3: consume some memory
    gct.eatMemory();
    // Step 4: determine amount of memory left after consumption
    freeMem = r.freeMemory();
    System.out.println("free memory after creating array: " + freeMem);
    // Step 5: run the garbage collector, then check freeMemory
    //r.gc();
    freeMem = r.freeMemory();
    System.gc();
    System.out.println("free memory after running gc(): " + freeMem);
    System.out.println(" Vector size = "+GCTest.ve.size());
    If u Run using System.gc , you will be able to see that the Free Memory is not increase

  • Runtime.getRuntime().exe()  communications

    Hi all,
    I'm currently trying to launch a large set of commands.
    I've benchmark Java so: Runtime.getRuntime().exe() is as fast as ProcessBuilder().
    What design pattern shall use to optimise the "concurrent time" ?
    Fit listener / event model well for this application ? Do you know any example ?
    Thanks you
    Victor

    Thanks you a lot..
    I've found this example, it looks good :
    package introduction.sample;
    import java.io.IOException;
    import java.util.concurrent.ArrayBlockingQueue;
    import java.util.concurrent.Callable;
    import java.util.concurrent.Future;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    public class sample2 {
    ThreadPoolExecutor threadPoolExecutor = null;
         public sample2()
         super();
         threadPoolExecutor = new ThreadPoolExecutor(5,10,5,TimeUnit.MINUTES, new ArrayBlockingQueue(10));
         public static void main(String[] args) throws IOException
              sample2 s = new sample2();
              s.checkThreadPoolExecutor();
              System.out.println("I am done with calling all threads- waiting for threads to finish");
              s.threadPoolExecutor.shutdown();
              try {
                   while (!s.threadPoolExecutor.awaitTermination(1000L, TimeUnit.MILLISECONDS)) {
                   // awaiting termination of all the threads here.
              catch(Exception e)
                   System.out.println("Exception while waiting fot threads to finish");
                   s.threadPoolExecutor.shutdown();
              System.out.println("Bye bye");
         private void checkThreadPoolExecutor(){
              for(int i = 0; i <10;i++)
              testMethod(i);
              System.out.println("I am done with i:" + i + " in checkThreadPoolExec");
         private void testMethod(int i){
              TestThread thread = new TestThread(i);
              Future<Integer> future = threadPoolExecutor.submit(thread);
    class TestThread implements Callable<Integer>{
         int i =0;
         String sample = null;
         public TestThread(int i)
              this.i = i;
         @Override
         public Integer call() {
              System.out.println("I am thread-"+i + "and sleeping for 1 min");
              try
                   Thread.sleep(1000*5);
              }catch(InterruptedException ie){
                   System.out.println("some one woke me up");
              try{
                   String test = sample.substring(0,1);
              }catch(Exception e){
                   throw new RuntimeException(e);
              return i;
    //source: http://forums.sun.com/thread.jspa?forumID=534&threadID=5367842Edited by: phpvik on Apr 21, 2009 9:27 AM
    Edited by: phpvik on Apr 21, 2009 9:35 AM
    Edited by: phpvik on Apr 21, 2009 9:36 AM

Maybe you are looking for

  • Save to PDF in TextEdit - Error While Printing

    When I try to save a text file to PDF I receive the error message - "Error while printing".  This only seems to be happening to text files I open or create in TextEdit.  It works fine if I log in as a different user.  I've run repair permissions and

  • HASH JOIN or NESTED LOOP

    I've been asked to check if HASH JOIN is more suitable than NESTED LOOP(which CBO chose by default) for the following query. SELECT CM_DETAILS.TASK_ID FROM GEN_TYPE, CM_DETAILS WHERE ( ( ( ( ( CM_DETAILS.STAT_CODE < 8 ) AND ( GEN_TYPE.TASK_ID = CM_DE

  • Set field in enhacement doesnu00B4t work

    Hello Collegues. I´ve done a enhacement on ERP_H component. I added a field to the view Headerdetail called "name", but when I set a value in UI, I haven´t read this field in abap code. The SET method (SET_NAME) in the context node is ok, in debug I

  • Help with small office PBX system.

    Hello all, I'm looking for any help or advice here. We have an old Panasonic PABX, 3 external CO lines and 16 extension lines (only 8 in use). Question 1. We have CO1 connected to the fax/broadband number. C02 and CO3 connected to our other number. H

  • Gray screen after boot and blue screen with stripes

    Hi, I have a MacBook Pro Mid 2011 with Mavericks (came with Snow Leopard). History: One day i was working and things were too slow. I tried to restart but it was taking too long to close all the programs. So I forced shut down by holding the power bu