Question

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);
            }
    }
}
Was it helpful?

Solution 2

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"};

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top