Executing C-program inside Java

Hello, my situation is that I am using an open source which is written in C.
I execute this program using the following code.
        Process proc=null;
        try{
            proc=Runtime.getRuntime().exec(cmds);
            System.out.println("Execute");
        catch(IOException ioex){
            System.out.println(ioex);
        try{
            proc.waitFor();
        catch(InterruptedException irex){
            System.out.println(irex);
        if(proc.exitValue()==0){
            System.out.println("The command is normally and sucessfully terminated.");
        }where the "cmds" is a normal command line argument using for executing the open source program.
For example,
prompt>./osprogram<input_file

ok

Similar Messages

  • Executing unix statements inside java

    How do you execute unix statements inside a java program? I need to execute a unix executable shell_prog.ksh from inside a java program.

    By the way, executing the "ls" command from within Java will not do anything unless you capture the output stream of the process running the "ls" command and display it:
    try
    Process p = Runtime.getRuntime.exec("ls");
    BufferedReader read = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;
    while( (line = read.readLine()) != null)
    System.out.println("OUT>>>" + line);
    catch(IOException ioe)
    ioe.printStackTrace(System.err);
    System.exit(1);
    }

  • Execute DOS command inside java

    I have a java program that reads each new user from an inputfile and writes that same user to an output file. The program works fine and is shown below:
    import java.io.*;
    public class FileStreamsTest {
    public static void main(String[] args) {
    try {
    File inputFile = new File("newbousrs.txt");
    File outputFile = new File("outagain.txt");
    FileInputStream fis = new FileInputStream(inputFile);
    FileOutputStream fos = new FileOutputStream(outputFile);
    int c;
    while ((c = fis.read()) != -1) {
    fos.write(c);
    fis.close();
    fos.close();
    } catch (FileNotFoundException e) {
    System.err.println("FileStreamsTest: " + e);
    } catch (IOException e) {
    System.err.println("FileStreamsTest: " + e);
    What I would like to do after each write is to execute a DOS command that looks something like this: supervsr.exe -USER username -PASS password -IMPORTUSERS importfile.txt
    The DOS command above will add each user to the system I want to as the loop goes through each user record.
    How do I execute the DOS command above inside java?

    Tried what but still having a problem...here is my code:
    import java.io.*;
    public class ReadSource {
    public static void main(String[] arguments) {
    try {
    FileReader file = new FileReader("newbousrs.txt");
                                  //FileWriter letters = new FileWriter("outagain.txt");
                                  //PrintWriter pw = new PrintWriter(new FileWriter("outagain.txt"));
    BufferedReader buff = new BufferedReader(file);
                                  Runtime rt = Runtime.getRuntime();
    boolean eof = false;
    while (!eof) {
    String line = buff.readLine();
    if (line == null)
    eof = true;
    else
    System.out.println(line);
                                                 Process proc = rt.exec("\\Blowfish\\droot\\Program Files\\Business Objects\\BusinessObjects 5.0\\supervsr.exe -USER xxxxx -PASS yyyy -IMPORTUSERS \\Blowfish\\droot\\accsp\\public\\newusers\\newbousrs.txt");
                                                 //System.out.println(line.substring(4, 10));
                                                 //System.out.println(line.substring(3,line.indexOf(',',3)));
    buff.close();
    } catch (IOException e) {
    System.out.println("Error -- " + e.toString());
    There error I get is this:
    C:\jakarta-tomcat-4.0.3\webapps\webdav\WEB-INF\classes\accsp>java ReadSource
    NU,Public,Steve Mcnealy,Steve Mcnealy,U,N,N,Y,N,N,PC,F,Y,N,N
    Error -- java.io.IOException: CreateProcess: \Blowfish\droot\Program Files\Busin
    ess Objects\BusinessObjects 5.0\supervsr.exe -USER accsp -PASS fish -IMPORTUSERS
    \Blowfish\droot\accsp\public\newusers\newbousrs.txt error=3

  • How to execute external program in java?

    My question is how to execute an external program in java.
    I need to call a unix command in java.
    Thanks.

    it depends on what you are trying to do. Following are the two methods
    1. Runtime.exec() : this method allows you just to call an external program as a seperate process
    2. JNI (Native Interface) :- As of right now only C and C++ are supported by this method. This method allows you to directly call the C/C++ methods from JAVA

  • Executing external program (non-java)

    Hello,
    I just started programming Java. I installed SunForum3.2 on SunRay some days ago and I was faced with the problem that all that the people who are registered with the GateKeeper-Software are not shown anywhere. So I developed a small app, that read out a file containing the output of the command "registrar -q" ( displays all registered users including their SunForum-name ). Now some people not working on the SunRay-platform would like to connect as well to the SunForum-users. For this reason I'd like to execute "registrar -q" periodically and directly use the output from and within a Java-app but I couldn't find a way to execute the program "registrar -q" so far.
    Thanks for your help.
    Thomas

    Process p = Runtime.getRuntime().exec( "registrar -q" );
    Then read the Process's input stream, which should give you the stdout of your command. There are plenty of full code examples of how to do this floating about, and you should have no problem with it.

  • Executing another program with Java?

    I'm relatively new to Java. I'd like to build a process-monitoring program that will allow me to determine the status of certain processes on the machine. In order to do this I need to know if Java can execute (and then of course read the output of) another program, in this case, the Unix 'ps' command.
    Thanks.
    David

    yeah: look at the java.lang.Runtime and java.lang.Process APIs, specifically Runtime.exec . There are a ton of discussions about those APIs in this forum, so you can probably find some code examples as well, if you do a search... Take care.

  • Pocket PC -Problem executing external program from java

    Hi,
    I'm developing an application on Dell Axim x51 PDA. I am using mysaifu jvm. The application needs to execute an external program (.exe) for which I'm using the Runtime class.
    I get java.io.IOException: The system cannot find the file specified.
    I have verified that the file exists. ( i used File class to check if the file exists)
    here's the part of code :
    Runtime rt = Runtime.getRuntime ();      
    File sktScan = new File("\\My Documents\\RFID\\ScktScan.exe");
    if(sktScan.exists())
    System.out.println("FILE EXISTS");
    String command = sktScan.getAbsolutePath();
    process = rt.exec (command);
    System.out.println("Socket Scan Path is : "+command);

    You have acces to "java.lang.Runtime currentRuntime.exec()" method ? in my case NetBeans IDE dont give me for my compilation with :
              microedition.configuration     CLDC-1.1     
              microedition.profiles     MIDP-2.0

  • Executing a program via Java

    Hi there, 1st post for me...
    I'm trying to write a program to open applications via a menu bar. To begin with I'm just trying to open a text document. Eventually I want to use this at work to open different applications. I'm VERY new to Java and I'm stuck on this. It compiles fine, but no text doc opening. Any help mucho appreciated.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class ApplicationList2 extends JFrame {
    private JMenuItem itsInput = new JMenuItem();
    public ApplicationList2() {
    super("Application List");
    setSize(300, 225);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JMenuItem kr1 = new JMenuItem("App1");
    itsInput.addActionListener (new kr1());
    JMenuItem kr2 = new JMenuItem("App2");
    JMenuItem kr3 = new JMenuItem("App3");
    JMenuItem kr4 = new JMenuItem("App4");
    JMenuItem kr5 = new JMenuItem("App5");
    JMenu m1 = new JMenu("Application");
    m1.add(kr1);
    m1.add(kr2);
    m1.addSeparator();
    m1.add(kr3);
    m1.add(kr4);
    m1.addSeparator();
    m1.add(kr5);
    JMenuBar jmb = new JMenuBar();
    jmb.add(m1);
    setJMenuBar(jmb);
    setVisible(true);
    private class kr1 implements ActionListener {
    public void actionPerformed(ActionEvent e) {
    Object esrc = e.getSource();
    if (esrc instanceof MenuItem && e.getActionCommand()=="App1") {
    try {
    String[] commands = new String[]{"C:/WINNT/system32/notepad.exe","C:/Main/TestDoc.txt"};
    Process child = Runtime.getRuntime().exec(commands);
    } catch (IOException a) {
    public static void main(String[] arguments) {
    ApplicationList2 md = new ApplicationList2();
    }

    ok, I'm back to:
    if (e.getActionCommand().equals("App1")) {
    try {
    String[] commands = new
    ds = new
    String[]{"Notepad.exe","C:\\Main\\TestDoc.txt"};
    Process child =
    child = Runtime.getRuntime().exec(commands);
    } catch (IOException a) {
    still nothing happening; can somebody take a minute
    to try on their machine? I'm pretty lost! :)I'm not going to run it on my machine. How about doing some debugging? Do something like this:
    if (e.getActionCommand().equals("App1")) {
      System.out.println("Hey, at least I know I'm getting into this block of code");
      ... (your other code which tries to launch Notepad goes here)
    }Because at this point, do you even know if the problem is that of launching notepad versus not getting to the code which tries to launch it?

  • Execute external program from java in the same virtual machine

    hello,
    I need some help. here is what i need: i'm developing a test tool and i need to execute the application to be tested from my test tool in the same virtual machine so that i can be able to connect to that application and catch events like clicking and so on.
    problem is that i do not know how to launch the application i want to test in the same virtual machine as the test tool.
    any help would be good,
    thanks

    problem is that i do not know how to launch the
    application i want to test in the same virtual
    machine as the test tool.Just invoke the main class of that application.
    You probably don't want to hear this, but writing a test tool is not easy if you are going to try to catch events etc. It's probably a bit too hard for you if you don't know how to invoke an app within the same VM.
    Kaj

  • Can we able to run java program inside  javascript

    Hi all
    can we able to run java program inside javascript or integrate java with javascript.....whether its possible...

    No. You can't execute Java code from within a JS script in Acrobat/Reader.

  • How to execute dos command in Java program?

    In Perl, it has System(command) to call dos command.
    Does java have this thing?
    or any other way to execute dos command in java program?
    Because i must call javacto compile a file when the user inputed a java file name.

    Look in the Runtime class, it is implemented using the Singleton design pattern so you have to use the static method getRuntime to get its only instance, on that instance you can invoke methods like
    exec(String command) that will execute that command in a dos shell.
    Regards,
    Gerrit.

  • How Can I execute a java program using java code?

    {color:#000000}Hello,
    i am in great trouble someone please help me. i want to execute java program through java code i have compiled the java class using Compiler API now i want to execute this Class file through java code please help me, thanks in advance
    {color}

    Thanks Manko.
    i think my question was not clear enough.. actually i want to run this class using some java code . like any IDE would do i am making a text editor for java, as my term project i have been able to complie the code usign compiler api and it genertaes the class file but now i want to run this class file "THROUGH JAVA CODE" instead of using Java command. I want to achive it programatically. do you have any idea about it.. thanks in advance

  • Executing Unix shell from Java Program

    Hi,
    I have written a java application using Maverick J2sshtools API which connects to a Unix box using SSH.The program authenticates with the remote box successfully,but It dosen't return the environment info or execute the test script.Have attached the complete code.
    package shellInteraction;
    import com.maverick.ssh.*;
    import com.maverick.ssh2.Ssh2Client;
    import com.maverick.ssh2.Ssh2Context;
    import com.maverick.ssh2.Ssh2PasswordAuthentication;
    import com.sshtools.net.*;
    import java.io.*;
    import java.util.Iterator;
    import java.util.Vector;
    public class JavaShell{
         public static void main(String[] args) {
              SshConnector con = null;
              SshClient ssh = null;
              ShellProcess process = null;
              Shell shell = null;     
              try{
                   // Create a session to remote host
                   con = SshConnector.getInstance();
                   ssh = connectionSetup(con);
                   System.out.println(ssh);
                   // Start a session and do basic IO
                   if (ssh.isAuthenticated()) {
                        shell = new Shell(ssh);
                        System.out.println("Authenticated");
                        if(shell.getEnvironment().hasEnvironmentVariable("hostname"))
                             System.out.println("We are connected to " + shell.getEnvironment().getEnvironmentVariable("hostname"));
                        //System.out.println("Remote operating system is " + shell.getEnvironment().getOperatingSystem());
                   //     boolean isWindows = shell.getEnvironment().getOSType()==ShellEnvironment.OS_WINDOWS;
                        //if(shell.getEnvironment().hasEnvironmentVariable("USERPROFILE")) {
                             //System.out.println("User home is " + shell.getEnvironment().getEnvironmentVariable("USERPROFILE"));
                        //} else if(shell.getEnvironment().hasEnvironmentVariable("HOME")) {
                             //System.out.println("User home is " + shell.getEnvironment().getEnvironmentVariable("HOME"));
                        // Commands only executed for Unix OS
                        //if(!isWindows) {
                             // Execute a script
                             traverseDirectory(shell);
                   shell.exit();
                   ssh.disconnect();
                   System.out.println("Shell has exited");
              } catch(Throwable t) {
                   t.printStackTrace();
         private static void traverseDirectory(Shell shell) throws Exception{
              System.out.println("\n\nTraverse Directory");
              // Execute a simple script than prints a directory tree
              ShellProcess process = shell.execute("bash test.sh ");
              try{
                   process.expect("Total directories", 1000, true);
                   System.out.print(process.toString());
              } catch (ShellTimeoutException ex1) {
                   System.out.println("TRAVERSE Expect operation timed out. Sending interrupt to kill the process");
                   process.interrupt();
              }finally {
                   process.close();
         static private Ssh2Client connectionSetup(SshConnector con)throws SshException{
              Ssh2Client ssh = null;
              final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
              try {
                   System.out.print("Hostname: ");
                   String hostname = reader.readLine();
                   int idx = hostname.indexOf(':');
                   int port = 22;
                   if(idx > -1) {
                        port = Integer.parseInt(hostname.substring(idx+1));
                        hostname = hostname.substring(0, idx);
                   System.out.print("Username [Enter for " + System.getProperty("user.name") + "]: ");
                   String username = reader.readLine();
                   if(username==null || username.trim().equals(""))
                        username = System.getProperty("user.name");
                   System.out.println("Connecting to " + hostname);
                   * Create an SshConnector instance
                   con = SshConnector.getInstance();
                   // Lets do some host key verification
                   HostKeyVerification hkv = new PasswordHostKey();
                   con.setSupportedVersions(SshConnector.SSH2);
                   * Set our preferred public key type
                   con.getContext(SshConnector.SSH2).setHostKeyVerification(hkv);
                   ((Ssh2Context)con.getContext(SshConnector.SSH2)).setPreferredPublicKey(Ssh2Context.PUBLIC_KEY_SSHDSS);
                   * Connect to the host
                   ssh = (Ssh2Client)con.connect(new SocketTransport(hostname, port), username, true);
                   * Authenticate the user using password authentication
                   Ssh2PasswordAuthentication passwordAuthentication = new Ssh2PasswordAuthentication();
                   System.out.print("Password: ");
                   passwordAuthentication.setPassword(reader.readLine());
                   if(ssh.authenticate(passwordAuthentication)!=SshAuthentication.COMPLETE) {
                        System.out.println("Authentication failed!");
                        System.exit(0);
              }catch(Exception ex1) {
                   throw new SshException(ex1.getMessage(), ex1.getCause());
              return ssh;
    When I execute the program
    Hostname:****
    Username [Enter for thaya]: **
    Connecting to CATL
    The connected host's key (ssh-dss) is
    b6:85:91:6b:8b:ea:cb:40:b5:6f:01:2e:66:78:7f:62
    Password: *****
    SSH2 CATLMSXP62:22 [kex=diffie-hellman-group1-sha1 hostkey=ssh-dss client->server=aes128-cbc,hmac-sha1,none server->client=aes128-cbc,hmac-sha1,none]
    Authenticated
    Traverse Directory
    com.maverick.ssh.ShellTimeoutException: The shell did not return to the prompt in the given timeout period 10000ms
         at com.maverick.ssh.Shell.A(Unknown Source)
         at com.maverick.ssh.Shell.execute(Unknown Source)
         at shellInteraction.ShellInteraction.traverseDirectory(ShellInteraction.java:108)
         at shellInteraction.ShellInteraction.main(ShellInteraction.java:68)
    This is the error message what i get.

    use code tags if you want a response,
    ive done the same thing once using
    ssh2.ethz.ch ie:
    import ch.ethz.ssh2.Connection;
    import ch.ethz.ssh2.ServerHostKeyVerifier;
    import ch.ethz.ssh2.Session;
    the code looked something like this:
    try
                   conn.connect(new ServerHostKeyVerifier() {
                        public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey) throws Exception {
                             return true;
                  conn.authenticateWithPassword(username, password);
                  try {
                       sess = conn.openSession();
                   } catch (java.lang.IllegalStateException e) {
                        return;
    //                    JOptionPane.showMessageDialog(null, "Could not autheticate.\nCheck username and password.\nTerminating.", "Authentication Failed", JOptionPane.ERROR_MESSAGE);
    //                    System.exit(-1);
                   sess.requestPTY("dumb", 50, 50, 0, 0, null);
                   sess.startShell();
              }and after that sess has getStdIn() and getStdOut() that get the streams from which you read and write.

  • Is it possible to execute SAPGUI scripts from java program?

    Hi everyone..
         I need to develop an java applications that executes the SAPGUI script or any technique that execute set of transaction as client.
         Is it possible to execute SAPGUI scripts from java program? if so, how it can be achieved? is there any other technique to achieve above mention scenario?.
         it will be more helpful, if docs related to that are shared..
         Thanks in advance

    Oh, bummer. Would be much more convenient if I could just use iTunes for everything. Can't stand WMP. I wonder if WinAmp might be a good compromise?
    Thanks for this answer . . .
    Sharon

  • Executing a webservice through Java Program

    Hi,
    I need to execute an webservice in my java program.
    I also have the requirmnet of executing a BAPI.
    I am using JCO for executing BAPI.
    Can anyone help me out in executing a webservice in Java Program.
    Regards
    Praveen

    Hi,
    Check
    http://help.sap.com/saphelp_nw04/helpdata/en/24/d0ff2f5d872a468b4643e1fa740569/frameset.htm
    and
    http://java.sun.com/developer/technicalArticles/J2EE/j2ee_ws/
    for consuming a WS
    Check http://help.sap.com/saphelp_nw04/helpdata/en/76/4a42f4f16d11d1ad15080009b0fb56/frameset.htm for BAPI called from Java
    Eddy
    PS. Which type of SDN Ubergeek/BPX suit are <a href="/people/eddy.declercq/blog/2007/05/14/which-type-of-sdn-ubergeekbpx-suit-are-you">you</a>?

Maybe you are looking for

  • Show file size coming from UCM

    I need to show the size of a file that comes from Oracle UCM and the file size should be shown in Kilobytes, the file size is in bytes so I've divided in 1024 for the number in kilobytes I have the following source code and the continuous result bein

  • NT Realm and Properties Files

    Hi, Does anyone experience similar problem. I am using NT Realm using a user already define in my NT domain. The properties File for WLS required that password be present for the system user. Having this when I start weblogic, I can log onto WLS with

  • Opening external files in Director Projector... *URGENT*

    Hi, this should be really basic, but I just can't work it out... I want to open external files (but kept in the same root directory as my projector file) from a mouse/button click in my projector. I don't know any Lingo, but I am assuming it should b

  • Invoices not showing in VF24.

    Can someone help, I have creatyed 10 invoices this morning and they have been processed in vf04 without any errors. These need to go into an invoice list but when I check vf24 the invoices are not visbale. I have checked vf24 for all item but still t

  • Photosmart 7520 black ink not working

    My brand new 7520 appears to have given up work already. Black ink is out of order.During printing it started to generate unprinted stripes and after two pages no more black ink was put on paper.Although the almost new cartridge should still do it, I