How to execute a shell command in java?

here, my environment is redhat 7, jdk 1.5.
i don't know how to use the shell command in java.
i want to use this function:
#include <stdlib.h>
int system(const char * string);
please give me some ideas. and Thank you so much if coming with a little demo.

i know i should use JNI. because i have to use C lib.
but i have already use JNI to wrapper the original code the cpp code and java code is :
//: appendixb:UseObjImpl.cpp
//# Tested with VC++ & BC++. Include path must
//# be adjusted to find the JNI headers. See
//# the makefile for this chapter (in the
//# downloadable source code) for an example.
#include <jni.h>
#include <stdlib.h>
extern "C" JNIEXPORT void JNICALL
Java_UseObjects_changeObject(
JNIEnv* env, jobject, jobject obj) {
jclass cls = env->GetObjectClass(obj);
jfieldID fid = env->GetFieldID(
cls, "aValue", "I");
jmethodID mid = env->GetMethodID(
cls, "divByTwo", "()V");
int value = env->GetIntField(obj, fid);
printf("Native: %d\n", value);
env->SetIntField(obj, fid, 6);
env->CallVoidMethod(obj, mid);
value = env->GetIntField(obj, fid);
system("preprocess -path sha.c");
printf("Native: %d\n", value);
} ///:~
//: appendixb:UseObjects.java
// From 'Thinking in Java, 2nd ed.' by Bruce Eckel
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
class MyJavaClass {
public int aValue;
public void divByTwo() { aValue /= 2; }
public class UseObjects {
private native void
changeObject(MyJavaClass obj);
static {
// System.loadLibrary("UseObjImpl");
// Linux hack, if you can't get your library
// path set in your environment:
System.load(
"/root/jproj/UseObjImpl.so");
public static void main(String[] args) {
UseObjects app = new UseObjects();
MyJavaClass anObj = new MyJavaClass();
anObj.aValue = 2;
app.changeObject(anObj);
System.out.println("Java: " + anObj.aValue);
} ///:~
i modify this two file which is from TIJ-2edition.
the output is
Native: 2
Native: 3
Java: 3
but what i want to be executed "preprocess -path sha.c" does not work.
i have change the command to, such as "df", "ls" etc. but none of them works
please help me.

Similar Messages

  • How to execute a shell command?

    What class and method should I use to set an environment variable on a local system? And how do I execute a shell command in Java?
    Thanks!

    I don't know about setting environment variables from java, but I do know how to execute system commands (and from there you could modify environment variables).
    Use Runtime.getRuntime().exec()
    There are quite a few pitfalls with using this though...
    1. It's platform dependent
    2. Doing this creates a Process. If this process has output, you need to read this, otherwise the output buffer will overflow, and that would be bad... Input is not so bad (either supplying it or not ;)
    3. If you use Win for example, and want to do a "dir", there are complications, as there is no dir.exe file, and hence it can't be executed... Do a search for this topic, there's plenty on how to get around it.
    Anyway, there's plenty more info on Runtime.getRuntime().exec(), have a look around.
    Cheers,
    Radish21

  • How to execute unix shell script from Java ...

    Hi,
    Anyone know how to execute unix shell script from Java?
    Suppose I have several shell scripts written in perl or tcl or bash.
    I just want to catch the output of that script.
    Is there any ready to use module/object for this?
    Please let me know, this is quite urgent for my study assigment.
    Thanks in advance,
    Regards,
    me

    Look up Runtime.exec()

  • How to Execute Power Shell Command From Windows Application.

    Hi All Experts,
    I want to execute power shell commands from my windows application.
    Is it possible ?
    Please let me know your comments..
    Thanks.

    I have not tried this, but apprently it is easy as in the sample pasted below. please see this article for more details
    http://geekswithblogs.net/Norgean/archive/2012/09/19/running-powershell-from-within-sharepoint.aspx.
    Let me know how it goes...
    public string RunPowershell(string powershellText, SPWeb web, string param1, string param2) {
    // Powershell ~= RunspaceFactory - i.e. Create a powershell context
    var runspace = RunspaceFactory.CreateRunspace();
    var resultString = new StringBuilder();
    try
    // load the SharePoint snapin - Note: you cannot do this in the script itself (i.e. add-pssnapin etc does not work)
    PSSnapInException snapInError;
    runspace.RunspaceConfiguration.AddPSSnapIn("Microsoft.SharePoint.PowerShell", out snapInError);
    runspace.Open();
    // set a web variable.
    runspace.SessionStateProxy.SetVariable("webContext", web);
    // and some user defined parameters
    runspace.SessionStateProxy.SetVariable("param1", param1);
    runspace.SessionStateProxy.SetVariable("param2", param2);
    var pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(powershellText);
    // add a "return" variable
    pipeline.Commands.Add("Out-String");
    // execute!
    var results = pipeline.Invoke();
    // convert the script result into a single string
    foreach (PSObject obj in results)
    resultString.AppendLine(obj.ToString());
    finally
    // close the runspace
    runspace.Close();
    // consider logging the result. Or something.
    return resultString.ToString();
    Ok. We've written some code. Let us test it.
    var runner = new PowershellRunner();
    runner.RunPowershellScript(@"
    $web = Get-SPWeb 'http://server/web' # or $webContext
    $web.Title = $param1
    $web.Update()
    $web.Dispose()
    ", null, "New title", "not used");
    -Sangeetha

  • How to execute a Unix Command in java

    Hi, Iam trying to execute a unix command on Sun Solaris by passing that command to a java program. How can I achieve this?
    Thanks in advance.

    Have a look at the javadoc around the Runtime.exec() method. If the command is a shell command then you might have to execute a shell as well as the command.
    For example, if you wanted to run a unix command 'ls -l > output.txt' the you might have to pass the following string into the exec() method,
    "/bin/sh ls -l > output.txt'

  • How to execute any cmd command from java application?

    Hi all,
    How to execute or call any command of cmd from java application??
    Is there any method to do so??
    Or, is it possible to do it using Runtime.exec() ??? And if so, how to use it, please explain with ab example...
    I'll highly appreciate....
    Thank you.

    If google would be the best option, then I would not be on Sun's forums and I would not have asked experts like you, sir !! :-)
    Neway, I got the solution from PhHein !!
    Good link indeed..
    Cheers..

  • How to execute the ldapsearch command by java class in linux os?

    hi,all
    I want to query the users by ldapsearch command. I call the command in my java class. In windows, It work well. But in linux , there haven't any result. My test program is following:
    ===============
    import java.util.*;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.LineNumberReader;
    public class test{
    public static Vector queryAllUser(){
    try{
    Vector v=new Vector();
    String cmdquery="ldapsearch -h localhost -b\"dc=metasphere,dc=com\" \"uid=*\" uid ";
    //String cmdquery="ls -la";
    Process process=Runtime.getRuntime().exec(cmdquery);
    System.out.println("cmdquery:"+cmdquery);
    InputStreamReader ir=new InputStreamReader(process.getInputStream());
    LineNumberReader input = new LineNumberReader (ir);
    System.out.println("input="+input);
    String line;
    while ((line = input.readLine ()) != null){
    System.out.println("Line:"+line);
    if(line.startsWith("uid")){
    String temp=line.substring(line.indexOf(":")+1,line.length());
    v.add(temp);
    return v;
    }catch(Exception e){
    e.printStackTrace();
    System.out.println("runtime error:"+e.getMessage());
    return null;
    public static void main(String argv[]){
    Vector v=queryAllUser();
    for(int i=0;i<v.size();i++){
    System.out.println((String)v.get(i));
    ================
    In fact, when I execute the command: ldapsearch -h localhost -b"dc=metasphere,dc=com" "uid=*" uid
    in linux prompt, the screen show the results:
    version: 1
    dn: uid=toppymgt,dc=metasphere,dc=com
    uid: toppymgt
    dn: uid=qutao,dc=metasphere,dc=com
    uid: qutao
    dn: uid=zz,dc=metasphere,dc=com
    uid: zz
    dn: uid=z,dc=metasphere,dc=com
    uid: z
    dn: uid=admin,dc=metasphere,dc=com
    uid: admin
    dn: uid=alan,dc=metasphere,dc=com
    uid: alan
    dn: uid=misssixty,dc=metasphere,dc=com
    uid: misssixty
    dn: uid=channelv,dc=metasphere,dc=com
    uid: channelv
    What's reason? Please help me. Thx.

    If there have a bugs in Linux OS. Please help me!

  • How to execute MS DOS command through Java program???

    Dear Sir,
    I want to run a MS-DOS command through my Java program. I have tried "Dir" command but no other command which takes command line args doesn't work at all. Please help.
    import java.io.*;
    class CommandPrompt
         public static void main(String[] args)
              try
                   File file = new File("C:/Temp/Java");
                   String[] cmd = {"command.com","/c","md folder"};
                   String[] envp = {""};
                   Process m;
                   String s = "";
                   m = Runtime.getRuntime().exec(cmd,null,file);
                   BufferedReader buf = new BufferedReader(new InputStreamReader(m.getInputStream()));
                   while ((s = buf.readLine())!=null)
                        System.out.println(s);
              catch (Exception ex)
                   System.out.println("Exception is "+ex);
                   ex.printStackTrace();

    1. This forum is for Swing-related issues only. This question should be posted to the "Java Programming" forum.
    2. Please enclose your sample code in code blocks; it's much easier to read that way. See here for how it's done: http://forum.java.sun.com/faq.jsp#messageformat
    3. Please provide more information, like what error messages you got and what OS you're running. For instance, if you're running WinXP, Win2k or NT4, your command processor should be "cmd.exe", not "command.com". When I made that change, your program worked for me.

  • Executing a shell command

    Hi,
    I'm new hier and have a short question. How do I execute a shell command from Java code?
    Have a nice day and lot of fun
    Yury

    Search the forum. This is explained well in other threads

  • Executing shell commands from Java.

    I want to execute shell commands in Java using the Runtime.exec( String ) method.
    The method works fine under Linux OS, but under Windows '98 the method didn't work at all!
    For example the following call: Runtime.exec( "dir" ) throws an exception showing that the command was not completed. If I replace dir with ls under Linux all is good. What is the problem with the Microsoft Windows '98 ? Is there any solution at my problem ?!
    thx in advance!

    hey JSarmis,
    You can help me... "ls" doesn't work for me on linux.. using Runtime.exec, some commands work, others don't... you may hold the key to what i need? How did u get "ls" to work?

  • Execute shell command from Java

    Hi all,
    I need some idea for executing shell script from Java programe.
    For example i have start.sh script in /tmp/start.sh  folder of unix server.
    I want to execute shell script from local java code.
    Any idea on this.

    Hi,
           Read the following articles/posts, maybe this could help you:
          How to execute shell command from Java
    Running system commands in Java applications | java exec example | alvinalexander.com
    Want to invoke a linux shell command from Java - Stack Overflow

  • How to execute unix shell script in webdynpro?

    hi all,
      We have some iquirement of executing script in unix.If anyone know How to execute unix shell script in webdynpro?
    best regard
    reefish

    Ree,
    1. Find SSH client for windows, then execute SSH with Runtime.exec() on local host with arguments like remote host, auth, command to execute etc.
    2. Get SSH client in Java and execute SSH commands on remote host using pure Java API.
    Don't ask me for links, Google works today, I checked this
    Valery Silaev
    SaM Solutions
    http://www.sam-solutions.net

  • Executing the top command through Java in linux

    I am trying to execute the top command in Java as
    Runtime.getRuntime().exec("top -n 1 >a.log");
    But the command is not working in linux only through java.When i run the same command through the prompt it is working fine.Also all other commands are working fine.Is there any issue with top in linux?

    flounder wrote:
    Try reading [this article|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html]. If it does not answer your problem then try seaching for other similar articles.
    The cited article does provide an answer to the problem since it explains how the shell meta character '>' must be interpretted by a shell. The code as presented does not invoke a shell.

  • How to execute dir dos command in Runtime Execution

    Hi All,
    Does anybody know how to execute the dir command in DOS in the runtime execution
    for example,
    when we open the command prompt,
    c:\Documents and Settings\java> e:
    e:\cd java
    e:\dir *.*
    how we can list the directory in runtime execution?

    Process childProcess = Runtime.getRuntime().exec("cmd /C dir *.*");or try with
    ProcessBuilder pb = new ProcessBuilder("cmd /C dir *.*");
    Process childProcess = pb.start();
    NOTE: We can use the ProcessBuilder class from J2SE 5.0+.
    for further reference check the below link
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=3
    and don't forget to go through API documentation for java.lang package
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/package-summary.html
    and if you want to implement it through Java which provides you a list of Files & directories in the present directory here is an example of such code snippet REF:as insisted by my fellow poster.
    File file = new File("<present_directory_path>");
    if(file.isDirectory()){
       String fileNames[] = file.list();
            for(String fileName:fileNames)
               System.out.println(fileName);
      fileNames = null;
            or for detailed info use
             File files[] = file.listFiles();
             for(File fileEntity:files)
                System.out.println("FILENAME:"+fileEntity.getName+",IS FOLDER:"+fileEntity.isFolder()+",ABSOLUTE PATH:"+fileEntity.toString()+"FILE SIZE:"+fileEntity.length());
             files = null;
    }and please do not forget to go through File API Documentation provided as recommended by my fellow poster.
    hope this might help :)
    REGARDS,
    RaHuL

  • Execute a DOS command in java

    Hi all,
    Is it possible to execute a DOS command in java? If so, how do I do that?
    Also, if it is a Linux machine, may I execute a Linux command in java?
    Thanks for your help.
    Regards,
    Bernard

    First, define 'command'.
    You can run external programs with Runtime.exec (eg. Runtime.getRuntime().exec("notepad");) but there are a few drawbacks regarding that method.
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

Maybe you are looking for

  • Portege M800-PPM81E - remote control installation issue

    Hello Guys, I have a problem to install remote control on this notebook. First of all the winbond CIR driver doesnt work, I try on diffrent operation systems... the same message..... "There is a problem with this Windows installer package. A program

  • CSA & Novell Client

    We run a Novell network and our primary authentication client is the Novell client. I've setup CSAMC v6 and have been tuning for the past couple of days. I seem to have a problem with the Novell client login script. Whenever I login, the search drive

  • Faxing PDF files made from cfdocument

    We recently upgraded to mx and we instituted the cfdocument tag to create our pdf files that we send as faxes or email attachments. Our faxes are not being printed correctly if they are sent to a standard fax machine. However the pdf file looks fine

  • Broken DC's

    While transfering the application to the Assembly server I found some of DC's broken. So I want to know how can i overcome the situation. <b>The point that I want to highlight is that when I deploy the DC's on the local machine it do not show any bui

  • Re-Linking After Effects CS5 files

    I moved an After Effects project file and now it is not linked with several of the files within the project.  I tried using the "create proxy" "replace proxy" and "replace footage" but in all cases, the file is imported with the name of the file on t