Launching command containing pipe from Java

Hi,
i have some troubles to launch a command containing pipe from java.
I've tried to backslash the pipe but it still not work.
Maybe someone has an idea about that :
head -102050 /data/a_very_big_file | tail -5
the idea is to get 5 lines in the middle of a very big file.
To launch commands from java i use i think the classical way,
something like :
Process p = Runtime.getRuntime().exec(commande[0], this.envp, new File(this.pathExecution));
I obtain this error :
ERROR : head: invalid option -- 5
ERROR : Try `head --help' for more information.
Thanks for your help,
kevin.

kevleb wrote:
yes same result...
but i think the problem come from the fact
that when you pipe your result of a command,
you launch an other process (is that true).i don't know if another process is launched (the probability is rather high, though)
but even if that's the case, from the time you rely on a shell and not directly on exec(), i think it shouldn't be a problem to include a | inside the command ; i don't have an idea why it gives you that message error :\

Similar Messages

  • Command line args from java to C++

    Hi
    I want to pass command line arguemnts argc and argv from java to C++. I have browsed the net and most of them suggested that I declare the jni statement with jObjectarray.
    I saw an example at http://www.csc.calpoly.edu/~fouzi/crossroads/Arguments.c
    It said
    #include "/home/java/linux/jdk118/include/jni.h"
    #include "Arguments.h"
    #include <stdio.h>
    JNIEXPORT void JNICALL
    Java_Arguments_setArgs (JNIEnv *jenv, jobject job, jobjectArray oarr)
    /* obtain the size the the array with a call to the JNI function
    GetArrayLength()                              */
    jsize argc = (*jenv)->GetArrayLength(jenv, oarr);
    /* Declare a char array for argv */
    char const* argv[128];
    int i;
    for (i = 1; i < argc + 1; i++) {
    /* obtain the current object from the object array */
    jobject myObject = (*jenv)->GetObjectArrayElement(jenv, oarr, i-1);
    /* Convert the object just obtained into a String */
    const char str = (jenv)->GetStringUTFChars(jenv,myObject,0);
    /* Build the argv array */
    argv[i] = str;
    /* print the argv array to the screen */
    printf ("argv[%i] = %s\n",i,argv);
    /* Free up memory to prevent memory leaks */
    (*jenv)->ReleaseStringUTFChars(jenv, myObject, str);
    // Increment argc to ajust the difference between Java and C arguments
    argc++;
    // Call a pipeline simulator function which uses command line arguments
    start(argc,argv);
    return;
    That is what I have where the start method is declared like this:
    void start(int argc, /* Argument count */ char argv[] / Argument strings */) {
    But I get a warning when I build the C routine. The warning arises when I am calling the start method.
    The warning says:
    f:\jni\dsaccess.c(711) : warning C4090: 'function' : different 'const' qualifiers
    f:\jni\dsaccess.c(711) : warning C4024: 'start' : different types for formal and actual parameter 2
    Can you help?
    Thanks
    Lakshmi

    1. Your array building looks bogus: Are you missing an index?
    2. You claim to be calling a "method". Are you? Or is it a subroutine?

  • Unix Named pipes from Java

    Hello,
    My problem is with a unix named pipe which I have to write to. To do it, I have to use a FileOutputStream. It works fine when some process is reading the named pipe. My problem is when there is no process reading the pipe, my Java app gets blocked in the open method of the FileOutputStream.
    What we want is to open the FileOutputStream without blocking, although there is no process reading the pipe.Is it possible from Java? Is there anything similar to the unix NON_BLOCK?
    Thank you in advance.
    RCG@

    Hi,
    I think, in UNIX you would get the same problem, at least if you are writing then.
    By NON_BLOCK you would not be blocked, but you would get an error each time you try to write. So in UNIX in most cases the blocking is quite adequate: you want to "listen", until someone "calls", and then continue.
    I assume you want to open the pipe first to see if you can access it successfully.
    For this, try the same trick like with C in UNIX:
    Open that pipe first for reading. So there is a reading process: your JVM.
    Does this help you?
    Regards,
    Hartmut

  • Launching jvm in solaris from java...

    I have a problem launching jvm from java in solaris...
    java.io.IOException: "/opt/XX/YY/jre/bin/java": not found
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:53)
    at java.lang.ProcessImpl.start(ProcessImpl.java:65)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:451)
    But when I give /opt/XX/YY/jre/bin/java from my console it's working fine...
    what could be the problem ?? (I mean the path is correct..)
    Message was edited by:
    chaos_begins_here

    When I try to System.exec() a program that doesn't exist, I get the following:
    java.io.IOException: foo: not found
    Note that foo (the program I tried to exec) is not in quotes. Check the strings you are passing to exec() to make sure there are no extra quotes. It's possible the difference in format is due to different java versions, but the point is to sanity check the strings you're passing.

  • Clear Command Line Console from Java

    Is there a way to clear the dos/shell console screen from a java program (the same way as cls would do in dos ir clear would do in unix) without making a Runtime.exec call??
    Thanks for your time
    wwe8

    What console window are you talking about?
    1- You might be starting a java application in a console window.
    2-Or it might be another console window.
    3-You might be starting a console window in java via Runtime.exec().
    For 1 and 2 you would need a JNI, platform specific solution. I believe the java testing tools do this, so if you got one of those it might provide an interface for this.
    If 3, then you would use the input stream to pass the command to the window.

  • Running command prompt externally from Java

    Hi,
    Does anyone know how to make a Java program that opens up the command prompt and runs certain commands? Thanks,
    Adam

    Read this before you use it:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Using KNI to launch a c program from java

    Here's my env: Garmin iQue 3600 running Palm OS 5, with iQue GPS installed. I've downloaded the most current cldc/midp packages.
    I'm modifying a j2me inventory app which needs to access a GPS library (in C) to suck lat/long values into the j2me app.
    How do you use KNI to load the needed library? I don't see a method in the System or Runtime classes of the KVM such as System.loadLibrary("nativelib") in JNI.
    Any help from someone who has done this would be greatly appreciated. This is my first app on a handheld, and I must be missing something?!

    Hi Harshad,
    I have a possible solution, but haven't had the time to do a proof-of-concept yet (working on another app now).
    I want to use CDC/Foundation Profile/Other Profiles as needed instead of CLDC/MIDP. The CDC has the full System class, with JNI functionality. I'd write a small library in C which is JNI aware, and able to call the native C library for the lat/long values my app needs.
    I should be able to load my C library from my app using System.loadLibrary() and invoke a native method I write to bridge the gap to the native method I need. My client device has lots of RAM and processor speed, so I think it would work.
    I was told that http://www.superwaba.com.br/en/default.asp these people also have a "VM" that contains JNI functionality, but haven't looked at it yet.

  • Execute an Unix command with pipe

    Hi,
    How do I execute a unix command with pipe from JAVA runTime.exec(cmd)? for example: "ls -l |wc -l"
    should return number of files. However, there is no output result. If I use "ls -l" as command argument, it gives file list.
    Here is my program:
    public static void main(String[] args) {
    try {
    Runtime runCmd = Runtime.getRuntime();
    System.out.println("sys testing");
    Process retProc = runCmd.exec(args[0]);
    BufferedReader bread = new BufferedReader
    (new InputStreamReader(retProc.getInputStream()) );
    String out = bread.readLine();
    while ( out != null ) {
    System.out.println(out);
    out = bread.readLine();
    DataOutputStream outSt = new DataOutputStream(retProc.getOutputStream() );
    outSt.writeChars(args[1]);
    outSt.flush();
    } catch (Exception ie) {
    ie.printStackTrace();
    Thanks in advance,
    Jeff

    I got my answer !
    No need to reply

  • Execute a Linux konsole command from Java

    Hy,I am having problems when trying to execute a command for konsole from java.
    This is a part of my code
    try {
         Runtime.getRuntime().exec("konsole");
    catch (IOException ex) {ex.printStackTrace();}this code opens the Linux konsole ; is the a method to append a command for Linux from java??
    Thanks

    OK
    this is what I am trying to do : by pressing a button
    in a JFrame I want to start Snort (the exact command
    is snort -c /etc/snort/snort.conf )
    What I want is the following: I press that button
    and the Konsole in Linux opens and that command to
    be executed I would just use the Process.getInputStream() method to retrieve what Snort said and display that in a JTextArea or something... why bother launching it in a terminal?
    I don't know if Snort is a daemon or what... if it's a daemon, you're not going to get much output from it... it'll fork itself into the background and exit.
    If it isn't a daemon, then you can either just redirect the output to a file, a la:
    konsole snort /etc/snort/snort.conf > /tmp/snort.outand do a "tail" sort of monitoring on the file. You could also just keep that process up in a different thread, and use a timer to periodically update the output into a JTextArea (this would also allow you to be notified when the process ended). Finally, you could wrap your command in a script and execute it that way.

  • 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..

  • Problems running external Win32 Multithread C-Program from Java

    hi,
    i just wrote a little java application which is calling my c-binary (a win32 multithread application written in pure ansi c) . let's call it "test.exe". i'm launching it via:
    Runtime.getRuntime().exec(cmd, new String[] { env }, dir)the program is started correctly and i get all test.exe outputs on my java console (therefor i grabbed the inputstream and errorstream of the process-object ...). so far so good.
    my problem is, that something with the multithreading seems to be wrong, when launching my test.exe from java!
    for example, i have the following line of code in my c-program (test.exe):
    WaitForSingleObject( g_hMutexREADY, INFINITE );if i launch my program as java process, this line seems to be ignored! that means, the program doesn't stop executing at this point (and is waiting for the mutex) but simply continues executing, causing the whole program to crash.
    if i run the same program directly from the winxp commandline all is working fine (that means: the threads of 'test.exe' synchronize each other correctly via the mutexes)!
    does anybody has an idea or have already had similar problems? maybe some win32 libraries are missing, could that be?
    thanks a lot.
    k4simir

    I just debugged a little bit through my c program. and it's not the multithrading stuff causing the error, but the win32 socket creation!
    my "multithreading c program" :-) is an ASR (automatic speech recognizer). it runs as socket server (on localhost) and accepts connections from clients (my java application). the client (java app) controls the ASR server (means start(), stop(), open(), close() ...). if the ASR server recognizes some user input, it will transfer it to the client for further processing.
    so far the theory. if i launch the ASR server via the window command line, the communication and the other stuff works fine. now i want my java app to launch the ASR server.
    the ASR fails, when it tries to create the socket:
    g_Vars.kServSock = socket( AF_INET, SOCK_STREAM, 0 );the error code returned by WSAGetLastError() is 10106! i didn't find this error code in the msdn! so i don't know what it means or what might be the problem.
    any ideas?
    thanks a lot!
    k4simir
    here's the full code:
    int     InitSocket( short sPortNr ) {
         int               iErr;
         SOCKADDR_IN     kMyAddr;
         iErr = StartUp();
         if( iErr != _SRC_OK ) {
              return _SRC_ERROR;
         // create server-socket:
         g_Vars.kServSock = socket( AF_INET, SOCK_STREAM, 0 );
         if( g_Vars.kServSock == INVALID_SOCKET ) {
              CleanUp();
              return _SRC_ERROR;
    int StartUp() {
         WORD wVersionRequested;
         WSADATA wsaData;
         int err;
         _DEBUGPRINT
         wVersionRequested = MAKEWORD( 2, 2 );
         err = WSAStartup( wVersionRequested, &wsaData );
         if ( err != 0 ) {
              return _SRC_ERROR;
         if ( LOBYTE( wsaData.wVersion ) != 2 ||
               HIBYTE( wsaData.wVersion ) != 2 ) {
              WSACleanup( );
              return _SRC_ERROR;
         return _SRC_OK;
    }

  • Write to i2c Register from java

    My setup: Java 1.5, SUSE Linux 10.2
    I'm trying to set registers over i2c.
    From command line this can be done using "i2cset [options] [bus_address] [chip_address] [register] [value] b".
    I'd like to do this without using the command line, directly from java (may be using JNI and some native libraries).
    I searched google, tried to find some examples at koders.com - but no luck.
    I hope someone can point me in the right direction... Any hint on this subject is highly appreciated!

    Yes, as I described, i don't want to use Runtime.exec().
    There are many registers which have to be set alternating, so i2cset has to be executed over 4 times a second - which is bad.
    I'm currently doing this in my application:
    ProcessBuilder pb = new ProcessBuilder(new String[] { I2C_SET_CMD, I2C_OPTION_NOQUESTIONS, I2C_BUS_ADRESS,
              I2C_CHIP_ADRESS, register, value, "b" });
    Process p = pb.start();
    int exitCode = p.waitFor();The problem is, that there are Filehandles left open (by i2cset?? I think so...) and that crashes linux after some hours of operating (to many open files).
    That's the reason, why I'm looking for a solution without Runtime.exec() and especially without using ic2set.
    At the moment I don't have native libraries or even native code to do this. Is there a native library which can be used from within java to set i2c Registers?
    Or is it somehow possible to do address i2c registers directly from java (whitout using native code)?

  • Launching Browser from Java when Browser URL is very  long

    Hi,
    I am trying to launch a browser from Java.
    I am doing the following.
    String command = "cmd" + "/c" + "start" + " browserURL";
    Process p = Runtime.getRuntime()exec(command);
    Note: My browserURL is very long.
    Now the browser is invoked. But the URL shown is incomplete and hence
    browser is unable to open the required application.
    Can someone help me in this.
    One way is to increase the buffer size on the command prompt?
    Is there any java command for this?
    Is there any other way to solve this issue.
    Thanks,
    AR

    this is my second time posting this, take note of it. I can't remember where i got it from, but credits go to the person that wrote it. It has helped me out thousands of times!!!
    to use, compile, then call from your program:
    org.newio.utils.BrowserLauncher.openURL("your url here")dfwtc
    package org.newio.utils;
    import java.io.File;
    import java.io.IOException;
    import java.lang.reflect.*;
    public class BrowserLauncher
        private static int jvm;
        private static Object browser;
        private static boolean loadedWithoutErrors;
        private static Class mrjFileUtilsClass;
        private static Class mrjOSTypeClass;
        private static Class macOSErrorClass;
        private static Class aeDescClass;
        private static Constructor aeTargetConstructor;
        private static Constructor appleEventConstructor;
        private static Constructor aeDescConstructor;
        private static Method findFolder;
        private static Method getFileType;
        private static Method makeOSType;
        private static Method putParameter;
        private static Method sendNoReply;
        private static Object kSystemFolderType;
        private static Integer keyDirectObject;
        private static Integer kAutoGenerateReturnID;
        private static Integer kAnyTransactionID;
        private static final int MRJ_2_0 = 0;
        private static final int MRJ_2_1 = 1;
        private static final int WINDOWS_NT = 2;
        private static final int WINDOWS_9x = 3;
        private static final int OTHER = -1;
        private static final String FINDER_TYPE = "FNDR";
        private static final String FINDER_CREATOR = "MACS";
        private static final String GURL_EVENT = "GURL";
        private static final String FIRST_WINDOWS_PARAMETER = "/c";
        private static final String SECOND_WINDOWS_PARAMETER = "start";
        private static final String NETSCAPE_OPEN_PARAMETER_START = " -remote 'openURL(";
        private static final String NETSCAPE_OPEN_PARAMETER_END = ")'";
        private static String errorMessage;
        private BrowserLauncher()
        private static boolean loadClasses()
            switch(jvm)
            default:
                break;
            case 0: // '\0'
                try
                    Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
                    macOSErrorClass = Class.forName("com.apple.MacOS.MacOSError");
                    Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
                    Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
                    Class aeClass = Class.forName("com.apple.MacOS.ae");
                    aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
                    aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class[] {
                        Integer.TYPE
                    appleEventConstructor = appleEventClass.getDeclaredConstructor(new Class[] {
                        Integer.TYPE, Integer.TYPE, aeTargetClass, Integer.TYPE, Integer.TYPE
                    aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[] {
                        java.lang.String.class
                    makeOSType = osUtilsClass.getDeclaredMethod("makeOSType", new Class[] {
                        java.lang.String.class
                    putParameter = appleEventClass.getDeclaredMethod("putParameter", new Class[] {
                        Integer.TYPE, aeDescClass
                    sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply", new Class[0]);
                    Field keyDirectObjectField = aeClass.getDeclaredField("keyDirectObject");
                    keyDirectObject = (Integer)keyDirectObjectField.get(null);
                    Field autoGenerateReturnIDField = appleEventClass.getDeclaredField("kAutoGenerateReturnID");
                    kAutoGenerateReturnID = (Integer)autoGenerateReturnIDField.get(null);
                    Field anyTransactionIDField = appleEventClass.getDeclaredField("kAnyTransactionID");
                    kAnyTransactionID = (Integer)anyTransactionIDField.get(null);
                    break;
                catch(ClassNotFoundException cnfe)
                    errorMessage = cnfe.getMessage();
                    return false;
                catch(NoSuchMethodException nsme)
                    errorMessage = nsme.getMessage();
                    return false;
                catch(NoSuchFieldException nsfe)
                    errorMessage = nsfe.getMessage();
                    return false;
                catch(IllegalAccessException iae)
                    errorMessage = iae.getMessage();
                return false;
            case 1: // '\001'
                try
                    mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
                    mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
                    Field systemFolderField = mrjFileUtilsClass.getDeclaredField("kSystemFolderType");
                    kSystemFolderType = systemFolderField.get(null);
                    findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder", new Class[] {
                        mrjOSTypeClass
                    getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType", new Class[] {
                        java.io.File.class
                    break;
                catch(ClassNotFoundException cnfe)
                    errorMessage = cnfe.getMessage();
                    return false;
                catch(NoSuchFieldException nsfe)
                    errorMessage = nsfe.getMessage();
                    return false;
                catch(NoSuchMethodException nsme)
                    errorMessage = nsme.getMessage();
                    return false;
                catch(SecurityException se)
                    errorMessage = se.getMessage();
                    return false;
                catch(IllegalAccessException iae)
                    errorMessage = iae.getMessage();
                return false;
            return true;
        private static Object locateBrowser()
            if(browser != null)
                return browser;
            switch(jvm)
            case 0: // '\0'
                try
                    Integer finderCreatorCode = (Integer)makeOSType.invoke(null, new Object[] {
                        "MACS"
                    Object aeTarget = aeTargetConstructor.newInstance(new Object[] {
                        finderCreatorCode
                    Integer gurlType = (Integer)makeOSType.invoke(null, new Object[] {
                        "GURL"
                    Object appleEvent = appleEventConstructor.newInstance(new Object[] {
                        gurlType, gurlType, aeTarget, kAutoGenerateReturnID, kAnyTransactionID
                    return appleEvent;
                catch(IllegalAccessException iae)
                    browser = null;
                    errorMessage = iae.getMessage();
                    return browser;
                catch(InstantiationException ie)
                    browser = null;
                    errorMessage = ie.getMessage();
                    return browser;
                catch(InvocationTargetException ite)
                    browser = null;
                    errorMessage = ite.getMessage();
                    return browser;
            case 1: // '\001'
                File systemFolder;
                try
                    systemFolder = (File)findFolder.invoke(null, new Object[] {
                        kSystemFolderType
                catch(IllegalArgumentException iare)
                    browser = null;
                    errorMessage = iare.getMessage();
                    return browser;
                catch(IllegalAccessException iae)
                    browser = null;
                    errorMessage = iae.getMessage();
                    return browser;
                catch(InvocationTargetException ite)
                    browser = null;
                    errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
                    return browser;
                String systemFolderFiles[] = systemFolder.list();
                for(int i = 0; i < systemFolderFiles.length; i++)
                    try
                        File file = new File(systemFolder, systemFolderFiles);
    if(file.isFile())
    Object fileType = getFileType.invoke(null, new Object[] {
    file
    if("FNDR".equals(fileType.toString()))
    browser = file.toString();
    return browser;
    catch(IllegalArgumentException iare)
    browser = browser;
    errorMessage = iare.getMessage();
    return null;
    catch(IllegalAccessException iae)
    browser = null;
    errorMessage = iae.getMessage();
    return browser;
    catch(InvocationTargetException ite)
    browser = null;
    errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
    return browser;
    browser = null;
    break;
    case 2: // '\002'
    browser = "cmd.exe";
    break;
    case 3: // '\003'
    browser = "command.com";
    break;
    case -1:
    default:
    browser = "netscape";
    break;
    return browser;
    public static void openURL(String url)
    throws IOException
    if(!loadedWithoutErrors)
    throw new IOException("Exception in finding browser: " + errorMessage);
    Object browser = locateBrowser();
    if(browser == null)
    throw new IOException("Unable to locate browser: " + errorMessage);
    switch(jvm)
    case 0: // '\0'
    Object aeDesc = null;
    try
    try
    aeDesc = aeDescConstructor.newInstance(new Object[] {
    url
    putParameter.invoke(browser, new Object[] {
    keyDirectObject, aeDesc
    sendNoReply.invoke(browser, new Object[0]);
    catch(InvocationTargetException ite)
    throw new IOException("InvocationTargetException while creating AEDesc: " + ite.getMessage());
    catch(IllegalAccessException iae)
    throw new IOException("IllegalAccessException while building AppleEvent: " + iae.getMessage());
    catch(InstantiationException ie)
    throw new IOException("InstantiationException while creating AEDesc: " + ie.getMessage());
    break;
    finally
    aeDesc = null;
    browser = null;
    case 1: // '\001'
    Runtime.getRuntime().exec(new String[] {
    (String)browser, url
    break;
    case 2: // '\002'
    case 3: // '\003'
    Runtime.getRuntime().exec(new String[] {
    (String)browser, "/c", "start", url
    break;
    case -1:
    Process process = Runtime.getRuntime().exec((String)browser + " -remote 'openURL(" + url + ")'");
    try
    int exitCode = process.waitFor();
    if(exitCode != 0)
    Runtime.getRuntime().exec(new String[] {
    (String)browser, url
    catch(InterruptedException ie)
    throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
    break;
    default:
    Runtime.getRuntime().exec(new String[] {
    (String)browser, url
    break;
    static
    loadedWithoutErrors = true;
    String osName = System.getProperty("os.name");
    if("Mac OS".equals(osName))
    String mrjVersion = System.getProperty("mrj.version");
    String majorMRJVersion = mrjVersion.substring(0, 3);
    try
    double version = Double.valueOf(majorMRJVersion).doubleValue();
    if(version == 2D)
    jvm = 0;
    } else
    if(version >= 2.1000000000000001D)
    jvm = 1;
    } else
    loadedWithoutErrors = false;
    errorMessage = "Unsupported MRJ version: " + version;
    catch(NumberFormatException numberformatexception)
    loadedWithoutErrors = false;
    errorMessage = "Invalid MRJ version: " + mrjVersion;
    } else
    if(osName.startsWith("Windows"))
    if(osName.indexOf("9") != -1)
    jvm = 3;
    } else
    jvm = 2;
    } else
    jvm = -1;
    if(loadedWithoutErrors)
    loadedWithoutErrors = loadClasses();
    suck my balls

  • Problem in executing Linux command from Java Programme.

    hi everybody,
    can anybody help me to solve one problem i have.
    i want to capture the output of linux command "grep" in my java programme.but it is not working properly .(maybe this sub-process doesn't have permission to read files)
    here is my code and corresponding outputs.
    import java.io.*;
    public class BSearch
    public static void main(String kj[])
    try
    Runtime rt=Runtime.getRuntime();
    String command="grep \"hello\" -r /usr/MyDir ";               
    Process rtProc=rt.exec(command);          
    InputStream is=rtProc.getInputStream();
    BufferedReader br =new BufferedReader(new InputStreamReader(is));     
    String line =null;
    while((line=br.readLine()) != null)
    System.out.println(br.readLine());
    br.close();
    catch(Exception e)
    System.err.println("Error in command "+e);               
    it finds "hello" pattern only in BSearch.class file although if i fire this command on LINUX prompt it
    shows all the files in /usr/MyDir which contain "hello" pattern.
    java programme output :
    Binary file /usr/MyDir/BSearch.class matches.
    linux command output :
    /usr/MyDir/one.txt: hello sdfs
    Binary file /usr/MyDir/BSearch.class matches.
    /usr/MyDir/two.txt: kjsdf hello sdfsdf
    will anybody help me solve this problem.

    It may be a Problem of Catching the Echoes back from the Processes...I have a Program which Captures the Echoes..see if it works
    import java.beans.PropertyChangeEvent;import java.beans.PropertyChangeListener;import java.beans.PropertyChangeSupport;import java.lang.ref.WeakReference;/** * Implements a proxy property change listener using a weak reference to avoid memory locking that would occur if it * was a strong reference. To understand this, we hve to understand that the property change listeners themselves are * hilding onto panels and other objects with strong java references. If the panel goes away while we are viewing an * object, we have a circular emory hold situation where the panel cant be collected because it has ahold of the * property and the property cannot because it has ahold of the pane. If we use weak references instead, then the hard * link between the listener and the producer is softened to almost nothing. */public class WeakPropertyChangeListener implements PropertyChangeListener {  /**   * A poperty change support object is included here so that the listener can remove   * himself from the listeners if the reference internally goes to null.   */  private PropertyChangeSupport pcs = null;  /** Holds the weak reference to the real listener. */  private WeakReference weakRef = null;  /**   * Constructs a new Proxy object for the given support and listener.   * @param pcs The property change support that this object will be using.   * @param pcl The real listener.   */  public WeakPropertyChangeListener(PropertyChangeSupport pcs, PropertyChangeListener pcl) {    if (pcs == null) throw new NullPointerException("pcs");    if (pcl == null) throw new NullPointerException("pcl");    this.pcs = pcs;    weakRef = new WeakReference(pcl);  } /** @see <{PropertyChangeListener}> */ public void propertyChange(PropertyChangeEvent changeEvent) {    Object referrant = weakRef.get();    if (referrant == null) {      pcs.removePropertyChangeListener(this);    } else {      ((PropertyChangeListener)referrant).propertyChange(changeEvent);    } } /** Returns true for comparison to referrant or this. */ public boolean equals(Object obj) {    if (obj instanceof WeakPropertyChangeListener) return super.equals(obj);    else if (obj != null)return obj.equals(weakRef.get());    else return false;  }}// snipet public void addPropertyChangeListener(PropertyChangeListener listener) {    this.propertyChangeSupport.addPropertyChangeListener(      new WeakPropertyChangeListener(this.propertyChangeSupport, listener));  } public void removePropertyChangeListener(PropertyChangeListener listener) {    this.propertyChangeSupport.removePropertyChangeListener(listener);  }

  • Problem while running dos command from java program

    Dear friends,
    I need to terminate a running jar file from my java program which is running in the windows os.
    For that i have an dos command to find process id of java program and kill by using tskill command.
    Command to find process id is,
    wmic /output:ProcessList.txt process where "name='java.exe'" get commandline,processid
    This command gives the ProcessList.txt file and it contains the processid. I have to read this file to find the processid.
    when i execute this command in dos prompt, it gives the processid in the ProcessList.txt file. But when i execute the same command in java program it keeps running mode only.
    Code to run this command is,
    public class KillProcess {
         public static void main(String args[]) {
              KillProcess kProcess = new KillProcess();
              kProcess.getRunningProcess();
              kProcess = new KillProcess();
              kProcess.readProcessFile();
         public void getRunningProcess() {
              String cmd = "wmic /output:ProcessList.txt process where \"name='java.exe'\" get commandline,processid";
              try {
                   Runtime run = Runtime.getRuntime();
                   Process process = run.exec(cmd);
                   int i = process.waitFor();
                   String s = null;
                   if(i==0) {
                        BufferedReader stdInput = new BufferedReader(new
                               InputStreamReader(process.getInputStream()));
                        while ((s = stdInput.readLine()) != null) {
                         System.out.println("--> "+s);
                   } else {
                        BufferedReader stdError = new BufferedReader(new
                               InputStreamReader(process.getErrorStream()));
                        while ((s = stdError.readLine()) != null) {
                         System.out.println("====> "+ s);
                   System.out.println("Running process End....");
              } catch(Exception e) {
                   e.printStackTrace();
         public String readProcessFile() {
              System.out.println("Read Process File...");
              File file = null;
              FileInputStream fis = null;
              BufferedReader br = null;
              String pixieLoc = "";
              try {
                   file = new File("ProcessList.txt");
                   if (file.exists() && file.length() > 0) {
                        fis = new FileInputStream(file);
                        br = new BufferedReader(new InputStreamReader(fis, "UTF-16"));
                        String line;
                        while((line = br.readLine()) != null)  {
                             System.out.println(line);
                   } else {
                        System.out.println("No such file");
              } catch (Exception e) {
                   e.printStackTrace();
              return pixieLoc;
    }     when i remove the process.waitFor(), then while reading the ProcessList.txt file, it says "No such file".
    if i give process.waitFor(), then it's in running mode and program is not completed.
    Colud anyone please tell me how to handle this situation?
    or Is there anyother way to kill the one running process in windows from java program?
    Thanks in advance,
    Sathish

    Hi masijade,
    The modified code is,
    class StreamGobbler extends Thread
        InputStream is;
        String type;
        StreamGobbler(InputStream is, String type)
            this.is = is;
            this.type = type;
        public void run()
            try
                InputStreamReader isr = new InputStreamReader(is, "UTF-16");
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                while ( (line = br.readLine()) != null)
                    System.out.println(type + ">" + line);
                } catch (IOException ioe)
                    ioe.printStackTrace(); 
    public class GoodWindowsExec
        public static void main(String args[])
            try
                String osName = System.getProperty("os.name" );
                String[] cmd = new String[3];
                 if( osName.equals( "Windows 95" ) )
                    cmd[0] = "command.com" ;
                    cmd[1] = "/C" ;
                    cmd[2] = "wmic process where \"name='java.exe'\" get commandline,processid";
                } else {
                    cmd[0] = "cmd.exe" ;
                    cmd[1] = "/C" ;
                    cmd[2] = "wmic process where \"name='java.exe'\" get commandline,processid";
                Runtime rt = Runtime.getRuntime();
                System.out.println("Execing " + cmd[0] + " " + cmd[1]
                                   + " " + cmd[2]);
                Process proc = rt.exec(cmd);
                System.out.println("Executing.......");
                // any error message?
                StreamGobbler errorGobbler = new
                    StreamGobbler(proc.getErrorStream(), "ERROR");           
                          // any output?
              StreamGobbler outputGobbler = new
                    StreamGobbler(proc.getInputStream(), "OUTPUT");
                          // kick them off
                errorGobbler.start();
                outputGobbler.start();
                // any error???
                int exitVal = proc.waitFor();
                System.out.println("ExitValue: " + exitVal);       
            } catch (Throwable t)
                t.printStackTrace();
    }when i execute the above code, i got output as,
    Execing cmd.exe /C wmic process where "name='java.exe'" get commandline,processid
    and keeps in running mode only.
    If i execute the same command in dos prompt,
    CommandLine
    ProcessId
    java -classpath ./../lib/StartApp.jar;./../lib; com.abc.middle.startapp.StartAPP  2468
    If i modify the command as,
    cmd.exe /C wmic process where "name='java.exe'" get commandline,processid  > 123.txt
    and keeps in running mode only.
    If i open the file when program in running mode, no contents in that file.
    If i terminte the program and if i open the file, then i find the processid in that file.
    Can you help me to solve this issue?

Maybe you are looking for

  • How can I get my wireless printer to join my wifi network?

    Since HP Setup Assistant doesn't work with Mavericks, is there another way to get my wireless printer connected to my new wifi network? This printer (HP Officejet Pro 8000 A809) worked just fine with Mavericks on my old wifi network. But my DSL provi

  • How do I get photos to preview in a second monitor on Bridge CC?

    This question must have been asked here before but I wasn't able to find the answer. Sorry if this is a repeat question... How do I get photos to preview in a second monitor on Bridge CC? It's harder to find the answer this than I expected it to be.

  • Dynamic table with dynamic drop-down list values

    Hi, I need to display a dynamic table with 2 columns on an interactive form. My Context is defined as below: Root StudentData     0..n StudentName StudentCourses     0..n Text Value The 1st column should display student name, 2nd column should displa

  • Why do my photos with my new cannon 7D have so much noise

    Hi, We just got a new cannon 7D last week and took it on vacation.  When we downloaded pictures, they have much worse noise especially at low light that our old outdated rebel xt.  The pictures look ok at regular magnification, but when zoomed in the

  • Having problem with Event function in Photostream

    Since the upgrade I find that the event function is no longer separating my uploaded photos by date of taking them so they are now all in one bucket so to speak instead of each day of the holiday. Why has this happened and have others had a similar i