Using unix rcp from java.

Hi,
I am trying to copy a file from a remote machine to the local file system in Java using rcp. I saw a post in this forum that talked about this, but no clear answer was ever posted. Currently we are trying to do this by using the .exec() class, but it doesn't work and doesn't throw an error either. Any help with this would be greatly appreciated.
Thanks,
Amber Taylor

Runtime.getRuntime().exec(...) is the way to do it. However, there are a few pitfalls to take care of.
You must capture all the output from the process, generally both on standard output and standard error, even if all you do is read the bytes from them and throw them away straight after. If you do not do this, chances are the process will either deadlock (and never finish), or die without failure.
My suggestion is to handle those two streams in two separate threads, and use waitFor() on the thread you start the process from to wait for it to finish. Also, check the error code you get back from the process after waitFor() returns.

Similar Messages

  • Using Unix commands from Java Application

    Hi,
    I need to write an Java application such that could run Unix commands in a Unix box.
    For example, my Java app needs to log in the Unix box, change directory (cd), create new folder (mkdir), list the current files in folder (ls), mount a new device (mount), etc.
    Thank you very much.
    Hung

    you can use java.lang.Runtime.exec to invoke OS commands, but if you're going to be completing a sequence that complicated and need to manage error handleing well, it might be best to just invoke a native method or write a shell script that does all of that stuff and then invoke that script via Runtime.exec . The Runtime class has limitations when you start invoking processes that require user input (like 'su'). Search the forums for more extensive examples on how to use Runtime.

  • Call an interactive UNIX command from java

    Hi,
    I want to call a UNIX command from java. When issue the command 'htpasswd -c filename username' on UNIX terminal, it asks for the new password and the then confirmation password again (yeah, unfortunately the htpasswd installed on our system does not allow you proivde the password on the command line. So have to work interactively ). Now, I have written a simple java program RunCommand.java. I am hardcoding the password for the htpasswd command in the file (in the real situation, password will be generated dynamically). I want to issue 'java RunCommand' on the UNIX command line and get back the command prompt without being asked for the password twice. The code is below, but the Outputstream does not work as expected. It always asks for inputs. Any idea? Many thanks.
    import java.io.*;
    public class RunCommand {
    public static void main(String args[]) throws Exception {
    String s = null;
    try {
    String cmd = "htpasswd -c filename username ";
    // run a Unix command
    Process p = Runtime.getRuntime().exec(cmd);
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    OutputStream stdOut = p.getOutputStream();
    String pswd = "mypassword";
    while ((s = stdInput.readLine()) != null) {
         s = stdInput.readLine();
         stdOut.write(pswd.getBytes());          
         stdOut.flush();
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null) {
    System.out.println(s);
    stdOut.close();
    stdInput.close();
    stdError.close();
    System.exit(0);
    catch (IOException e) {
    System.out.println("exceptions caught: ");
    e.printStackTrace();
    System.exit(-1);

    There are only about 9 billion responses a day on how to do this. Use the search feature.

  • Execute unix commands from Java

    Hi,
    I have a client application running on windows. This client should connect to a unix server and check for the existence of a file and display the result as "File found/File not found". In order to connect from windows to the unix server, I used the sockets and the connection is successfully established. The second part is to check for the presence of the file in unix server. I searched in google.com and the option I found to execute a unix command from java is the "Runtime.exec()". Runtime.exec is considered as the less effective (not a favorable) one.
    Is there any other option available (other than the Runtime) to execute the unix command from java? Can you please let me know.
    Thanks a lot
    Aishu

    So, please let me know how I can execute the above unix commands without Runtime.exec()You have a client and a server.
    You want something to run on the server, not the client.
    That means that something must in fact being running on the server before the client does anything at all.
    For example telnet. Or a J2EE server application.
    So is something like that running?
    If not then there absolutely no way to do what you want, even with Runtime.exec().
    If yes then what you do depends on what is running. So Runtime.exec() would be pointless if a J2EE server was running.

  • Excute unix script from java.

    Hi need to excute unix script from java application.
    My code is:
    public class Test
    public static void main(String args[])
         try{
         p = Runtime.getRuntime().exec("./qfe0"); //qfe0 is the name of the script.
    p.waitFor();
    catch(Exception e)
    e.printStackTrace();
    My problem is that using the waitFor() statement stuck the the script. if i don't use the waitFor() it works good but then i don't know when the script is finished.
    Any idea?

    The problem is likely to be that you script is either waiting for input or has filled the stdout buffer and you are not emptying it. Search this forum for this as its been answered many times before.

  • How execute Unix script from java?

    Can I execute Unix script from java?

    Yes. Using ProcessBuilder. And read [When Runtime.exec() wont|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html]. It's old, but pretty much all of it is still true.

  • How can i use Unix database in java?

    How can i use Unix database in Java?
    Message was edited by:
    JPro

    I have not a clue about FoxPro, but the db then is FoxPro and not Unix. The better question would be "How do I connect to FoxPro DB running on Unix with JDBC?".
    My answer to that would be, search the Internet for a JDBC driver.

  • Run a UNIX Script from java

    Hi,
    how can i run a unix script from java application. This java application is on windows.
    How can i do this.
    thanks,

    Hi,
    how can i run a unix script from java application.
    This java application is on windows.
    So I think it's safe to assume that the target script is on a remote unix server.
    Take a look at http://sourceforge.net/projects/sshtools/

  • Using word/excel from java (client or weblogic server)

    Hi everybody,
    i want to use excel / word functionality from java in two different variants:
    -> serverside
    -> clientside
    I tried the weblogic.comc and i got serveral classes but in the remote-package i got only a utitlity-class.
    My knowlege about COM is rather bad.
    Does anybody did this bevor and
    -> can say me, if it is correct, that i only got a utility-class (so how will i use it from the client ?!)
    -> has a example for using Excel / Word from Java in bea weblogic
    -> has a example for using Excel / Word directly in a client (not via rmi)
    Thanks
    Ciao
    Sven

    Sven, This is a really bad idea. Why don't you tell me
    what your trying to do and I wil surely give you a better alternative
    JRadecki
    "Sven Roesner" <[email protected]> wrote:
    >
    Hi everybody,
    i want to use excel / word functionality from java in two different variants:
    -> serverside
    -> clientside
    I tried the weblogic.comc and i got serveral classes but in the remote-package i got only a utitlity-class.
    My knowlege about COM is rather bad.
    Does anybody did this bevor and
    -> can say me, if it is correct, that i only got a utility-class (so how will i use it from the client ?!)
    -> has a example for using Excel / Word from Java in bea weblogic
    -> has a example for using Excel / Word directly in a client (not via rmi)
    Thanks
    Ciao
    Sven

  • Use a scanner from Java

    Hi all!, someone knows about an API that let me use a scanner from Java?
    without programing JNI code.
    thks in advance!.

    The Java Twain package from http://www.gnome.sk does exactly what you need. You do not have to bother about jni, you can get an image from the scanner directly from your java application.
    Erika

  • Issueing unix command from java

    I am using FTPConnection.java by Bret Taylor, for uploading files to remote linux portal. But i cannot issue any unix command from it . please anyone help me in this case?

    Read this:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    It'll explain it all. - MOD

  • Invoking unix executable from java

    How do I capture the RETURN VALUE from the Unix process (executable) invoked from java program

    After using Runtime.getRuntime() , and using runtime.exec(ProcessName), You get a Process object you can use waitFor() method of process. After that call process.getInputStream() and encapsulate in DataInputStream then onwards u can use readLine method to get value it is returned.
    S.M.Reddy.

  • Need to access/connect Remote Unix server from Java

    Please any one give me a direct solution for connecting a remote Unix server through telnet connection from java application. Thanks in advance..

    If I run the below program codes, in the console it is asking to enter username and password in manual but I need to give it automatically.
    The highlighted "root" is entered by the user manually using keyboard.
    Expected:
    I mean the username, password and some action is set to be automatic, so that it should not ask the user to enter the input from keyboard.
    import java.awt.Robot;
    import java.awt.event.KeyEvent;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import org.apache.commons.net.telnet.TelnetClient;
    import org.apache.commons.net.telnet.TelnetNotificationHandler;
    import org.apache.commons.net.telnet.SimpleOptionHandler;
    import org.apache.commons.net.telnet.EchoOptionHandler;
    import org.apache.commons.net.telnet.TerminalTypeOptionHandler;
    import org.apache.commons.net.telnet.SuppressGAOptionHandler;
    import org.apache.commons.net.telnet.InvalidTelnetOptionException;
    import java.util.StringTokenizer;
    * This is a simple example of use of TelnetClient.
    * An external option handler (SimpleTelnetOptionHandler) is used.
    * Initial configuration requested by TelnetClient will be:
    * WILL ECHO, WILL SUPPR
    * ESS-GA, DO SUPPRESS-GA.
    * VT100 terminal type will be subnegotiated.
    * <p>
    * Also, use of the sendAYT(), getLocalOptionState(), getRemoteOptionState()
    * is demonstrated.
    * When connected, type AYT to send an AYT command to the server and see
    * the result.
    * Type OPT to see a report of the state of the first 25 options.
    * <p>
    * @author Bruno D'Avanzo
    public class UnixConnect implements Runnable, TelnetNotificationHandler
        static TelnetClient tc = null;
         * Main for the TelnetClientExample.
        public static void main(String[] args) throws IOException
            FileOutputStream fout = null;
            /*if(args.length < 1)
                System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]");
                System.exit(1);
            String remoteip = "192.168.20.11";
            int remoteport;
            if (args.length > 1)
                remoteport = (new Integer(args[1])).intValue();
            else
                remoteport = 23;
            try
                fout = new FileOutputStream ("spy.log", true);
            catch (Exception e)
                System.err.println(
                    "Exception while opening the spy file: "
                    + e.getMessage());
            tc = new TelnetClient();
            TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT200", false, false, true, false);
            EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
            SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
            try
                tc.addOptionHandler(ttopt);
                tc.addOptionHandler(echoopt);
                tc.addOptionHandler(gaopt);
            catch (InvalidTelnetOptionException e)
                System.err.println("Error registering option handlers: " + e.getMessage());
            while (true)
                boolean end_loop = false;
                try
                    tc.connect(remoteip, remoteport);
                    Thread reader = new Thread (new UnixConnect());
                    tc.registerNotifHandler(new UnixConnect());
                    reader.start();
                    OutputStream outstr = tc.getOutputStream();
                    byte[] buff = new byte[1024];
                    int ret_read = 0;
                    do
                        try
                            ret_read = System.in.read(buff);
                            if(ret_read > 0)
                            outstr.write(buff, 0 , ret_read);
                            outstr.flush();
                        catch (Exception e)
                            System.err.println("Exception while reading keyboard:" + e.getMessage());
                            end_loop = true;
                    while((ret_read > 0) && (end_loop == false));
                    try
                        tc.disconnect();
                    catch (Exception e)
                              System.err.println("Exception while connecting:" + e.getMessage());
                catch (Exception e)
                        System.err.println("Exception while connecting:" + e.getMessage());
                        System.exit(1);
         * Callback method called when TelnetClient receives an option
         * negotiation command.
         * <p>
         * @param negotiation_code - type of negotiation command received
         * (RECEIVED_DO, RECEIVED_DONT, RECEIVED_WILL, RECEIVED_WONT)
         * <p>
         * @param option_code - code of the option negotiated
         * <p>
        public void receivedNegotiation(int negotiation_code, int option_code)
            String command = null;
            if(negotiation_code == TelnetNotificationHandler.RECEIVED_DO)
                command = "DO";
            else if(negotiation_code == TelnetNotificationHandler.RECEIVED_DONT)
                command = "DONT";
            else if(negotiation_code == TelnetNotificationHandler.RECEIVED_WILL)
                command = "WILL";
            else if(negotiation_code == TelnetNotificationHandler.RECEIVED_WONT)
                command = "WONT";
            System.out.println("Received " + command + " for option code " + option_code);
         * Reader thread.
         * Reads lines from the TelnetClient and echoes them
         * on the screen.
        public void run()
            InputStream instr = tc.getInputStream();
            try
                byte[] buff = new byte[1024];
                int ret_read = 0;
                do
                    ret_read = instr.read(buff);
                    if(ret_read > 0)
                       System.out.print(new String(buff, 0, ret_read));
                while (ret_read >= 0);
            catch (Exception e)
                System.err.println("Exception while reading socket:" + e.getMessage());
            try
                tc.disconnect();
            catch (Exception e)
                System.err.println("Exception while closing telnet:" + e.getMessage());

  • Using Inbound IDOC from Java system creation of Outbound delivery

    Dear Experts,
    The scenario we are having is really very interesting. Hopefully its a good learning for me and also for others also.
    The scenario is,
    After sales order creation the details will be sent to one Non SAP system (Java) for performing some tasks related to forwarding agent decision, shipping date and etc. Once the details are finalized in that Java system then, the details needs to be transferred to SAP as "Inbound IDOC" process. For this proposed to use the SAP Jco middle ware.
    Once the details transfered from Java system to SAP then, the outbound IDOC needs to get generated automatically. Assuming the stock for that sales order line item is available. Also one more complexity is, our client is using custom transaction (ZVl10C) for delivery creation.
    Now Query is,
    1. Which IDOC, message type and Functional module needs to be used for creating the delivery automatically..??
    2. As per assumption, stock of that sales order line item should be available. Due to some business reason the stock was removed during inbound IDOC transfer then, what will happen to the IDOC..?. How to avoid this situation..??
    3. As we told we are re going to use SAP Jco b/w SAP & Java system. In this case, how the data will get transfered from Java system to SAP..?
    Thanks in advance for the replies I am going to get
    Regards,
    VEL

    Thanks for the feedback. This question is resolved

  • Using ExecutorService class from java.util.concurrent package

    Dear java programmers,
    I have a question regarding the ExecutorService class from java.util.concurrent package.
    I want to parse hundreds of files and for this purpose I'm implementing a thread pool. The way I use the ExecutorService class is summarized below:
    ExecutorService executor = Executors.newFixedThreadPool(10);
            for (int i = 0; i < 1000; i++){
                System.out.println("Parsing file No "+i);
                executor.submit(new Dock(i));
            executor.shutdown();
            try {
                executor.awaitTermination(30, TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            executor.shutdownNow();However, the code snippet above creates all the 1000 threads (Dock objects) at once and loads them to the executor, and thus I'm worrying about memory leak. I haven't tested it on 1000 files yet but just on 50 small ones, and even if the program prints out "Parsing file No "+i 50 times at once, it executes normally the threads in the background.
    I guess the write way would be to keep the number of active/idle threads in the executor constant (lets say 20 if the thread pool's size is 10) and submit a new one whenever a thread has been finished or terminated. But for this to happen the program should be notified someway whenever a thread is done. Can anybody help me do that?
    thanks in advance,
    Tom

    Ok I found a feasible solution myself although I'm not sure if this is the optimum.
    Here's what I did:
            ExecutorService executor = Executors.newFixedThreadPool(10);
            Future<String> future0, future1, future2, future3, future4, future5, future6, future7, future8, future9;
            Future[] futureArray = {future0 = null, future1 = null, future2 = null, future3 = null, future4 = null, future5 = null,
            future6 = null, future7 = null, future8 = null, future9 = null};
            for (int i = 0; i < 10; i++){
                futureArray[i] = executor.submit(new Dock(i));
            }I created the ExecutorService object which encapsulates the thread pool and then created 10 Future objects (java.util.concurrent.Future) and added them into an Array.
    For java.util.concurrent.Future and Callable Interface usage refer to:
    [http://www.swingwiki.org/best:use_worker_thread_for_long_operations]
    [http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter10/concurrencyTools.html]
    I used a Future[] Array to make the code neater. So after that I submitted -and in this way filled up- the first 10 threads to the thread pool.
            int i = 9;
            while (i < 1000){
                for (int j = 0; j < 10; j++){
                    if (futureArray[j].isDone() && i < 999){
                        try{
                            i++;
                            futureArray[j] = executor.submit(new Dock(i));
                        } catch (ExecutionException ex) {
                            ex.printStackTrace();
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                try {
                    Thread.sleep(100); // wait a while
                } catch(InterruptedException iex) { /* ignore */ }
            executor.shutdown();
            try {
                executor.awaitTermination(60, TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            executor.shutdownNow();
        }Each of the future[0-9] objects represents a thread in the thread pool. So essentially I'm check which of these 10 threads has been finished (using the java.util.concurrent.Future.isDone() method) and if yes I replenish that empty future[0-9] object with a new one.

Maybe you are looking for

  • Web Service Testing Problem

    Hi All,         I create a new customize web service for service confirmation through Web UI in CRM7.0 .I activate the service in Productive mode .After that 2 new button is coming (WSDL and Test Page) in same page.when i click on WSDL button ,i got

  • About forms builder 6i's tab page

    when tab page is changed from one to another which triggers will be fired in order?? (click the topmost Tab Page ) thanks Edited by: user650991 on Apr 16, 2009 6:11 PM

  • I can't install Photoshop Elements 8 (using a disc)

    I know that my computer is working fine because other discs work, but when I put this disc in, nothing happens.  I called support and they referred me to Tech Support.  I am still not having any luck reaching anyone there!! I spent a lot of money on

  • Identifying the Logical Partition

    Hi Team , Please clarify, how we can identify the Logical disk name in Solaris OK prompt (like c0t0d0) using the physical name. Regards, R. Rajesh Kannan.

  • CR XI - "Out of memory" Error

    Crystal XI - Oracle 9i I have a report which has group sort all with totals for first certain number of accounts and hide the rest giving a total of displayed, hidden and a grand total, and when i run this report i am running into "Out of memory erro