4

I tried out a simple program to execute Linux command at run time. But the following program gets compiled and runs without any error, but the text file is not getting created as intended.Is there anything wrong in this program?

import java.io.*;
class ExecuteJava
{
    public static void main(String args[])
    {
            String historycmd = "cat ~/.bash_history >> Documents/history.txt";
            try
            {
                    Runtime runtime = Runtime.getRuntime();
                    Process proc = runtime.exec(historycmd);
            }
            catch(Exception e)
            {
                    System.out.println(e);
            }
    }
}
2
  • 2
    This code is attempting to write to a directory named Documents in the current directory the progam is running in. Does that directory exist? Commented Aug 19, 2013 at 23:10
  • @andy256 Yeah, it does. Commented Aug 19, 2013 at 23:29

2 Answers 2

2

Try accessing some of the functions Process provides. I'd start with exitValue. Typically a -1 indicates something went wrong while a 0 means nothing especially bad happened.

Also try InputStream and Error Stream, and read them fully. See if either has useful feedback for you.

Other than that, try what andy256 suggests in comments. Ensure the Documents directory exists in the executing directory of the program.

Sign up to request clarification or add additional context in comments.

Comments

1

The append operator >> is meant to be interpreted as part of the command shell. Use

String[] historycmd = 
           { "bash", "-c", "cat ~/.bash_history >> Documents/history.txt"};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.