Link to home
Start Free TrialLog in
Avatar of mkhan900
mkhan900

asked on

Execute a CommandLine Program from Java

I am trying to encrypt files through a java program. I am required to call a command line program to do this.
I am not sure if this is correct, please help

public class enCryptFiles
{
public static void main(String args[]) throws Exception
{
    String[] filenames;
    File f = new File(args[0]);
    filenames = f.list();
      for(int i=0; i< filenames.length; i++)
        {System.out.println(filenames[i]);
        // String cmmd = "filecrypt --encrypt "+ filenames[i] + " --user PublicKeyName";
         //System.out.println(cmmd);
           Process p = Runtime.getRuntime().exec("cmd /c start filecrypt --encrypt "+ filenames[i] + " --user PublicKeyName" );
   }}}    

Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

That's OK. You probably need to handle the process' streams though. Read this carefully

http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
try:

           Process p = Runtime.getRuntime().exec(new String[] { "cmd", "/c", "start", "filecrypt", "--encrypt", "filenames[i]", "--user", "PublicKeyName"} );

though by the looks start is unecessary and can be removed.
I'd also include the full path to your executable
and make sure you include the required command line options so the app does not prompt you for any input (or you will need to provide it) and run silently without any output.
Keeps the code simpler and avoids need to add the code shown in these examples
http://exampledepot.com/egs/java.lang/WriteToCommand.html
http://exampledepot.com/egs/java.lang/ReadFromCommand.html
Avatar of mkhan900
mkhan900

ASKER

Objects, I tried doing this. I tried printing the array variable, seems like variable "command" isn't getting assigned with the string.
Thanks for the help

public class enCryptFiles
{
      public static void main(String args[]) throws Exception
      {
         String[] filenames;
          File f = new File(args[0]);
          filenames = f.list();
          for(int i=0; i< filenames.length; i++)
        {
           String[] command = new String[] { "cmd", "/c", "start", "filecrypt", "--encrypt"+ filenames[i] + "--user", "PublicKeyName"};
         System.out.println(command);
         System.out.println(filenames[i]);
         Process p = Runtime.getRuntime().exec(command);
        }
    }
}    
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial