Runtime.exec() with get command output

hi,
How can i get output of command which i run with runtime.exec().
p.e.:
Process p;
Runtime r = Runtime.getRuntime();
p = r.exec("net use \\pc\dir pswd /user:username");
if command was done succesfully that in cmd is return this:
"The command completed successfully." I can get this text, but i dont know how.
Plese help
thank you
Palo

Look at the API for Process

Similar Messages

  • Runtime.exec() with .bat-files in a jar

    Hi All,
    I've written a java-Program, which calls .bat-files per Runtime.exec() for some OS-specific tasks.
    Everything works fine, but if I want to pack the whole code and the .bat-files into several jars, I can't get the bat-files to run. I have tried to get it to work with "getClass().getResource()" as I do the same for my Images, and the returned URL seems to be OK so far (something like jar:file:/c:/test.jar! testpkg/test.bat). I converted this URL into a String and tried to run Runtime.exec() with it, but I always get a Runtime-Exception.
    The String looks exactly like the URL, when I print them to console.
    These bat-files are essential for the application and I would not try to pack them into a jar if I hadn't to distribute this application as a signed applet to unknown users, too.
    I hope there is anyone out there who can tell me if and how it is possible to run an external program out of java, which is packed into a jar, so thanx in advance to any helpful replies.
    acdeka

    You can't run the .bats simply because the shell can't access it. You tell it to run a file that simply doesn't exist in the OS.

  • Runtime.exec() with language specific chars (umlauts)

    Hello,
    my problem is as follows:
    I need to run the glimpse search engine from a java application on solaris using JRE 1.3.1 with a search pattern containing special characters.
    Glimpse has indexed UTF8 coded XML files that can contain text with language specific characters in different languages (i.e. german umlauts, spanish, chinese). The following code works fine on windows and with JRE 1.2.2 on solaris too:
    String sSearchedFreeText = "Tür";
    String sEncoding = "UTF8";
    // Convert UTF8 search free text
    ByteArrayOutputStream osByteArray = new ByteArrayOutputStream();
    Writer w = new OutputStreamWriter(osByteArray, sEncoding);
    w.write(sSearchedFreeText);
    w.close();
    // Generate process
    String commandString = "glimpse -y -l -i -H /data/glimpseindex -W -L 20 {" + osByteArray.toString() + "}";
    Process p = Runtime.getRuntime().exec(commandString);
    One of the XML files contains:
    <group topic="service-num">
    <entry name="id">7059</entry>
    <entry name="name">T&#195;&#188;rverkleidung</entry>
    </group>
    Running the java code with JRE 1.2.2 on solaris i get following correct commandline
    glimpse -y -l -i -H /data/glimpseindex -W -L 20 {T&#195;&#188;rverkleidung}
    --> glimpse finds correct filenames
    Running it with JRE 1.3.1 i get following incorrect commandline
    glimpse -y -l -i -H /data/glimpseindex -W -L 20 {T??rverkleidung}
    --> glimpse finds nothing
    JRE 1.2.2 uses as default charset ISO-8859-1 but JRE 1.3.1 uses ASCII on solaris.
    Is it possible to change the default charset for the JVM in solaris environment?
    Or is there a way to force encoding used by Runtime.exec() with java code?
    Thanks in advance for any hints.
    Karsten

    osByteArray.toString()Yes, there's a way to force the encoding. You provide it as a parameter to the toString() method.

  • Runtime.exec() with japanese arguments?

    I'm trying to invoke a C++ executable from java using the Runtime.exec() method. The C++ application accepts a filename as a command line argument & opens the file. This C++ app is unicode enabled i.e. it can accept UTF-16 (wide char) parameters. Howevere, when i invoke this application using Java's Runtime.exec() and specify a japanese file name as an argument, the japanese characters get converted to '?' characters by the time they are received in the C++ application. I'm running this application on Windows 2K, default i.e. English version.
    Looking at the source code of Runtime class, it seems that the exec()
    function makes use of a native helper function - execInternal(). Does
    this function support the entire unicode range?
    Is there any way we can avoid the conversion of japanese characters to '?' characters? Also, is there any other alternative for invoking an external application with Unicode (Say, japanese) arguments?
    Please reply ASAP.
    Thanks!

    I have a very similar problem. I am invoking cvs through Runtime.exec, and I am using it to add and check in files with chinese characters in the name, and it is failing with the following cvs error:
    Could not add resource file &#32435;&#20986; in directory C:\test to repository: cvs add: nothing known about ??
    The error message comes from cvs, and I have been able to track it down to the call string I pass to exec. It is correct when passed in but the command fails. For laughs I tried to call something simpler, like mkdir:
    err mkdir ?? is: The filename, directory name, or volume label syntax is incorrect.
    It seems pretty clear to me that although the callstring is correct, the call to exec fails, and the special characters are replaced with questionmarks, which seems to me to be an encoding issue.
    Did you get any solution to your problem, or does anyoen else have an answer for this?

  • Runtime.exec() with envp[] array

    I ran into an unsual problem.
    If I set an env array variable to something (at least one pair), then certain applications fail to start through Runtime.exec(command[], env[]). For example, my own java classes that require various xml and ftp libraries. The particular exception has been mentioned on the forum ( ie. Unrecognized Windows Sockets error: 10106:).
    It has to do with environment variables not being set for new process. When I do NOT set env[] variable (or pass null) then current env is used in .exec() call and everything works fine.
    So my question is how do I set my environment variables and/or append them to existing set.Or said differently if I pass a non-null array, current env set is not copied over.
    thanks,
    eugene

    >
    It has to do with environment variables not being set for new process. When I do NOT set env[] variable (or pass null) then current env is used in .exec() call and everything works fine.
    So my question is how do I set my environment variables and/or append them to existing set.Or said differently if I pass a non-null array, current env set is not copied over.
    >
    If you're using 1.5, you can create a java.lang.ProcessBuilder object rather than calling Runtime.exec(). The ProcessBuilder inherits the environment of the calling process, but then allows you to update individual entries.
    In 1.4, I don't believe that you can get a complete copy of the invoker's environment.

  • Runtime.exec with spaces not working EVEN using String[]!!

    Hi everyone,
    I need to start the rmi registry from some code,and i need to pass it the classpath of two jars when initialising it. My problem is that the paths I set aren't taken when they contain a space.
    Here's the code:
    <code>
    String rmiRegistryCommandLine[] = new String[] {
    + System.getProperty("java.home")
    + "\\bin\\rmiregistry.exe\"",
    "-J-Djava.class.path=\""+System.getProperty("user.dir")+"\\MyJar.jar\"",
    "1099"};
                                            Runtime.getRuntime().exec(rmiRegistryCommandLine);
    </code>
    I know that Runtime.exec(String) tokenizes the input, which is why I'm not using it, but Runtime.exec(String[]) isn't supposed to tokenize the input. System.getProperty("user.dir") can contain a space, so I put quotes around that, but I need the -J-Djava.class.path in the same string. I tried breaking it up into two more separate strings but it didn't even run for normal non-space paths then. I am sure that if the whole -J-Dblah....upto MyJar.jar was in quotes then it would work, but I need the classpath in quotes separately as it could contain a space.
    Can anyone help me get this working?

    Ya, that's fine but the command line I want to pass is:
    d:\j2sdk1.4.0\bin\rmiregistry.exe -J-Djava.class.path=d:\my dir with spaces\MyJar.jar;d:\my more dir with spaces\MyJar2.jar 1099
    If I say
    arg[0]="d:\\j2sdk1.4.0\\bin\rmiregistry.exe";, that's finebut arg[1] is the problem
    if I say
    arg[1]="-J-Djava.class.path=d:\\my dir with spaces\MyJar.jar; d:\\my more dir with spaces\\MyJar2.jar";, then it definitely won't work on 9X machines and probably not on NT.
    if I break up arg[1] into:
    arg[1]="-J-Djava.class.path=";
    arg[2]="d:\\my dir with spaces\\MyJar.jar";
    arg[3]=";";
    arg[4]="d:\\my more dir with spaces\\MyJar2.jar";I'll need to put quotes around the two individual two class paths or else it won't work.
    I find though that if I put the classpath as follows
    d:\"my dir with spaces"\MyJar.jar then it seems to work.
    I think a regular expression function to search for any directory with spacees and then put quotes around it and reinsert it into the path would be the solution.

  • Runtime.exec with wget

    Hi,
    well i want to execute wget command in a java class and print sdout in the shell
    this is my code:
              try {
                   Process ls_proc = Runtime.getRuntime().exec("wget http://antimilkado.free.fr/ted/screenshot.png");
                   BufferedReader ls_in = new BufferedReader(new InputStreamReader(ls_proc.getInputStream()));
                   try {
                        while ((ls_str = ls_in.readLine()) != null) {
                             System.out.println(ls_str);
                   catch (IOException e) {
                        System.err.println(e);
                        System.exit(0);
              }I've tested with other basic command like ls and co., it works but not with a wget, nothing is printed...
    I guess my code is good and there is maybe a problem with wget command i don't know
    If someone gets it :)
    thx
    ++
    SHiSo

    1) Get the InputStream from the connection.
    2) Open a FileOutpupStream to the file you wish to write.
    3) Loop reading bytes from the InputStream and write them to the FileOutputStream until you get EOF.
    e.g.
    InputStream is = ...
    FileOutputStream os = ...
    byte[] buffer = new byte[4096];// or any size you want
    for (int count = 0; (count = is.read(buffer)) >= 0;)
    os.write(buffer, 0, count);
    4) flush() then close() the FileOuputStream.

  • Runtime.exec with a unix shell script

    I've done a lot of google'ing and haven't found a definitive answer to my question, including the JavaWorld article that is pointed to quite often. Scenario1 - The program calling Runtime.exec is running in /dir1 and I have a script called test.sh in /dir2 (neither directory are in the path). If I call Runtime.exec("test.sh", null, "/dir2"), I get java.io.IOException: test.sh: not found. However, if I do "touch test.sh" AND "chmod +x test.sh" in /dir1 and call the same exec, it works AND runs the script in /dir2 not /dir1?!?! Also, if I copy /dir2/test.sh /dir1/test.sh and I call exec("test.sh"), it works fine. Scenario2 - If I get rid of /dir1/test.sh and call exec("/dir2/test.sh", null, "/dir2") OR exec("/bin/sh test.sh", null, "/dir2") - both of those work. I just don't get Scenario1. Why does having the dummy executable test.sh in /dir1 allow it to run in /dir2 OR if the script is in the local directory of the process calling exec, why does it work without adding the path? It doesn't seem consistent. Seems like the working directory I specify isn't set before trying to run it or something. On the flip side, if I have a java class in /dir2 called test.class, I can call exec("java test", null, "/dir2") and it just runs without jumping through any hoops - although I think the explanation for that is that "java" is in the path. Let me know what you think.
    Gary

    I think the problem is that the three argument version of exec specifies the command to run (should be full path to it if it is not in the current dir), the environment, then the working directory. The working directory will not help java to find the command to run in the first place. The following does work as you say:
    Runtime.exec("/bin/sh test.sh",null,"/dir2");This is because the full path to the command (/bin/sh) is specified, that runs in directory /dir2 then tries to find test.sh which it finds there.
    Basically to run anything, you should specify the full path in the command, the working directory will not help java find it.
    Dave

  • Runtime class (with scp command)

    Hello
    I wrote a working code , but I think there may be a simpler way to do it.
    I would like to know if it's possible to use the Runtime class , to connect to a remote server and download a file to my computer, using scp command .
    something like:
    String command = "scp Username@server : fileWanted destinationPath";
                Runtime runtime = Runtime.getRuntime();
                Process child = runtime.exec(command);Something in this manner(obviously I will need to take care of the password issue).
    (A code sample will be great)
    thanks,Dave

    You might be interested in jsch, Java Secure Channel (BSD license), a pure-Java implementation of SSH2:
    http://www.jcraft.com/jsch/index.html
    See "ScpFrom.java" in "examples" directory.

  • Problem with getting bulk output in 2D char array in precompiler program

    In a ANSI dynamic SQL precompiler (Pro*C) program how do I obtain the bulk output of a column of string type (varchar or char) in a host variable array.
    I do not want to use reference semantics, instead want to use get descriptor directive. Is it possible to use 2 dimensional character array for getting the output?
    I am dynamically allocating memory for the host arrays.

    Consider asking this in the forum for C and C++ (OCI and OCCI).

  • Runtime.exec with Unix script

    I want to execute unix script xxx.sh that I write it for running something and I will execute that script via java class I use
    Runtime runTime = Runtime.getRuntime();
    Process procRun = runTime.exec("/xxx/yyyy/testing.sh");
    xxx and yyyy is path in my unix server and testing.sh is unix script
    when I run this class it return true result but that unix script doesn't working or execute following my program in java class
    please help me to solve this problem
    Regards,
    sobig

    when I run this class it return true result but that unix script doesn't
    working or execute following my program in java classwhat do you mean it returns true....
    and how do you know that it does not execute your script.... its probably going to be started as a bg process.... try doing something like creating a directory or something in the script .sh to be sure that it ran.... (just for testing).... im quite sure that it will execute a .sh file like that....

  • Stuck On Runtime.exec() with cmd.exe

    I've done my best to look through the forums and implement what's been said but I'm getting a problem where my whole Java program freezes when the exec() is executed. Can anyone tell me what I'm missing or have misunderstood ?
            try
                Process runSmodels = Runtime.getRuntime().exec("C:\\Windows\\System32\\cmd.exe lparse predict.pl | smodels 0");
                String smodelsOutput = new String();
                BufferedReader smodelsReader = new BufferedReader(new InputStreamReader(runSmodels.getInputStream()));
                String outputLine = smodelsReader.readLine();
                while(outputLine != null)
                    smodelsOutput += outputLine;
                    outputLine = smodelsReader.readLine();
                smodelsReader.close();
                System.out.println(smodelsOutput);
            catch(IOException exc)
                JOptionPane.showMessageDialog(rootPane, "Could not access Smodels.", "System Call Error", JOptionPane.ERROR_MESSAGE);
            }

    DarioAtUOW wrote:
    Pitfall 1 : Calling .exitValue(). My code doesn't do that.
    Pitfall 2 :Not enptying relevant streams. I do empty the input stream.
    Pitfall 3 : Assuming a command is an executable program. I don't do that, cmd.exe is in my command string explicitly.
    Pitfall 4 : As above in Pitfall 3.
    So, why accuse me of not reading the article ? You probably have many years of experience at Java, unlike me, who is just starting out with it at university.Pitfall 2 : Even though you are processing stdout you are not processing stderr! Always always always process both. This may or may not be the cause of your problem but by copying the process stderr to your System.err you may see why your process is stuck.
    Even Clippy, the Microsoft Office Assistant, could answer questions better than you have attempted to do.Ouch, I'm cut to the bone on your razor sharp wit. Phuck you.

  • Runtime.Exec with cmd and problem in waitFor

    Hi
    I am running
    Process p1 = Runtime.getRuntime().exec("cmd /c start /min <some.exe> <args to exe>");
    then I am checking
    Int ExitVal = p1.waitFor;
    If (ExitVal != 0) and so on.
    However, the problem is that the p1.waitFor does not really block the thread. It returns 0 and the program continues even though the some.exe has still not completed its execution.
    My guess is that Java is giving the exitcode of cmd.exe and not some.exe.
    If this analysis is correct, I am stumped. How do I get the exit code of some.exe?
    If my analysis is wrong, please help me in the right direction.
    Regards
    Shreekar

    "Enables a user to start a separate window in Windows
    from the MS-DOS prompt."<p>
    Again, I read it afterwards. However, another funny thing is happening now. Initially my command was
    "cmd start /min (some.exe) (some args) > somefile.txt"
    (I know I missed to show the output redirection in my original post.)
    </p>
    <p>
    Then I removed "start /min", it is working as expected.
    Then I removed the output redirection and now it hangs !!!
    I put back the output redirection and it is working. Does the output redirection make it wait in some way and force it to exit gracefully?
    </p>
    Any ideas?

  • Cisco css http keepalive is not working with GET command

    Dear all
    i have Cisco Css connected to Dell Server (via switch)
    Cisco CSS - 192.168.1.3 and Dell Server - 192.168.1.5
    Dell server is setup with windows 2009R2 and Apache HTTPD is version 2.2
    This server is dedicated to host multiple doamins with Apache lik
    www.abc.co.uk
    www.xyz.co.uk
    Now the clinet wants to setup the http keepalive  with specfic web page like /testpage.html  for all these domains. i have teseed with single URI. it is working the comamnds are
    config)# service serv1
    (config-service[serv1])# ip address 192.168.1.5
    (config-service[serv1])# keepalive type http
    (config-service[serv1])# keepalive method head    ( get i have not used due to hash mismatch with apche server, if i use GET it is not working)
    (config-service[serv1])# keepalive uri "/testpage.html"
    (config-service[serv1])# active
    It is working with single URI.  but how can i do the same thing for multiple doamins ?
    for multiple doamins do i need use script ? or can i use with commands ?
    if i need to use script the script is
    !no echo
    ! Filename: httptag-test
    ! Parameters: HostName WebPage HostTag
    ! Description:
    !       This script will connect to the remote host and do an HTTP
    !   GET method upon the web page that the user has asked for.
    !   This script also adds a host tag to the GET request.
    ! Failure Upon:
    !   1. Not establishing a connection with the host.
    !       2. Not receiving an HTTP status "200 OK"
    if ${ARGS}[#] "NEQ" "3"
            echo "Usage: httptag-test \'Hostname WebPage HostTag\'"
            exit script 1
    endbranch
    ! Defines:
    set HostName "${ARGS}[1]"
    set WebPage "${ARGS}[2]"
    set HostTag "${ARGS}[3]"
    ! Connect to the remote Host
    set EXIT_MSG "Connection Failure"
    socket connect host ${HostName} port 80 tcp
    ! Send the GET request for the web page
    set EXIT_MSG "Send: Failed"
    socket send ${SOCKET} "GET ${WebPage} HTTP/1.1\nHost: ${HostTag}\n\n"
    ! Send the HEAD request for the web page
    set EXIT_MSG "Send: Failed"
    socket send ${SOCKET} "HEAD ${WebPage} HTTP/1.1\nHost: ${HostTag}\n\n"
    ! Wait for a good status code
    set EXIT_MSG "Waitfor: Failed"
    socket waitfor ${SOCKET} "200 OK"
    no set EXIT_MSG
    socket disconnect ${SOCKET}sh w
    exit script 0
    in the script i have not used GET becasue, when CSS send GET request to apache it use hash, but apache is not able to respond with same hash and it shows that website is down. more information- click below url
    http://www.cisco.com/en/US/docs/app_ntwk_services/data_center_app_services/css11500series/v7.40/command/reference/CmdKeepC.html#wp1139668
    (config-keepalive) method
    I have uploaded in CSS with httptag-test file and applied these commands
    service comp.brit.co.uk-80
      keepalive port 80
      ip address 192.168.1.5
      keepalive frequency 10
    keepalive maxfailure 2
    keepalive retryperiod 10
    keepalive type script httptag-test "192.168.1.5 /testpage.html  www.abc.co.uk
    keepalive type script httptag-test "192.168.1.5 /testpage.html  www.xyz.co.uk
    but this script is not working
    my question is:
    1.do i need use script only to setup http keepalvie with webpage for multiple domains ?
    2.with out using script is there any solution like CICSCO  CSS commands  to setup http uril for multiple domains which are on 1 singl server.
    please help me asap

    Hello Muhammad,
    If you wish to use multiple domains for a URI  keep-alive check, and perform a HEAD request what Daniel mentioned is  correct.  You have to use a scripted keep-alive check on the service.  However, you should not use the default "ap-kal-httptag" script to do so  as it's limited to only 1 website (unless you modify the script).  You're best bet would be using the "ap-kal-httplist" script on the CSS  as it allows the checking of 2 different websites along with a webpage  to check for each site using HTTP HEAD method.
    !no echo
    ! Filename: ap-kal-httplist
    ! Parameters: Site1 WebPage1 Site2 WebPage2 [...]
    ! Description:
    !    This script will connect a list of sites/webpage pairs.  The
    !   user must simply supply the site, and then the webpage and
    !   we'll attempt to do an HTTP HEAD on that page.
    ! Failure Upon:
    !   1. Not establishing a connection with the host.
    !   2. Not receiving a status code 200 on the HEAD request on any
    !      one site.  If one fails, the script fails.
    ! Make sure the user has a qualified number of arguments
    if ${ARGS}[#] "LT" "2"
            echo "Usage: ap-kal-httplist \'WebSite1 WebPage1 WebSite2 WebPage2 ...'"
            exit script 1
    endbranch
    while ${ARGS}[#] "GT" "0"
            set Site "${ARGS}[1]"
        var-shift ARGS
        if ${ARGS}[#] "==" "0"
            set EXIT_MSG "Parameter mismatch: hostname present but webpage was not"
            exit script 1
        endbranch
        set Page "${ARGS}[1]"
        var-shift ARGS
        no set EXIT_MSG
        function HeadUrl call "${Site} ${Page}"
    endbranch
    exit script 0
    function HeadUrl begin
    ! Connect to the remote Host
    set EXIT_MSG "Connect: Failed to connect to ${ARGS}[1]"
    socket connect host ${ARGS}[1] port 80 tcp 2000
    ! Send the head request
    set EXIT_MSG "Send: Failed to send to ${ARGS}[1]"
    socket send ${SOCKET} "HEAD ${ARGS}[2] HTTP/1.0\n\n"
    ! Wait for the status code 200 to be given to us
    set EXIT_MSG "Waitfor: Failed to wait for '200' on ${ARGS}[1]"
    socket waitfor ${SOCKET} " 200 " 2000
    no set EXIT_MSG
    socket disconnect ${SOCKET}
    function HeadUrl end
    Rather  then modify the default "ap-kal-httplist" script on the CSS I would  simply define the arguments within the service configuration itself.   Something like the following (using your service example):
    service dell-192.168.1.5
    ip address 192.168.1.5
    keepalive type script ap-kal-httplist "www.abc.co.uk /testpage.html www.xyz.co.uk /testpage.html"
    active
    As  long as the server is configured to reply to host headers, and the page  is configured to retuen a "200 OK" the above service configuration  should work. If there are any errors simply run "show service  " to view why there was a failure. If there is a  failure, and the output from the command specified shows a line number  run the following command against the script to view at what point  (line) did the failure occur:
    show script ap-kal-httplist line-numbers
    Hope this helps!
    - Jason Espino

  • Runtime exec with blanks

    I there!
    i've a problem calling linux commands with blanks.
    eg:
    ---snip---
    String cpCommand = "cp /home/bullseye/my file.txt /tmp/tempFile.tmp";
    Process p = Runtime.getRuntime().exec(cpCommand);
    return p.waitFor()
    ---snip---
    i've tried with
    String cpCommand = "cp /home/bullseye/my\ file.txt /tmp/tempFile.tmp";
    and
    String cpCommand = "cp \"/home/bullseye/my file.txt\" \"/tmp/tempFile.tmp\"";
    but nothing works....
    could someone help me?!
    thx-a-lot

    I tried this command in Unix and it works.
    cp "/home/bullseye/my file.txt" /tmp/tempFile.tmp
    The java String for this will be
    String cpCommand = "cp \"/home/bullseye/my file.txt\" /tmp/tempFile.tmp";Hope this helps.
    vinod.

Maybe you are looking for