0

using this code:

   private String executeCommand(String cmd ) {

    Process p;
    try {
        p = Runtime.getRuntime().exec(cmd);
        BufferedReader br = new BufferedReader(
            new InputStreamReader(p.getInputStream()));

        while ((commandlineOutput = br.readLine()) != null){
                System.out.println("line:" + commandlineOutput);
             }
        p.waitFor();
                System.out.println (p.exitValue());

        p.destroy();
    } catch (Exception e) {}

  }
return commandlineOutput;
}

I run into the following problem: all commands that generate some output are executed normal, but some commands not generating output are not executed for instance : rm *.jpg is not working but mkdir is, I can not see the difference

I am quite a newbie, googled quite some time but this particular problem is never mentioned please help me out thanks

allard
  • 3
  • 4
  • What kind of output are you expecting by running `rm *.jpg`? Have you checked to see if the command is running? – nullByteMe Aug 24 '13 at 02:00
  • rm *.jpg when used from the command line generate no feedback to the user, it just deletes all jpg files in current dir. When copy paste the command as generated from the java program to a commandline it does work normaly The exit output from rm *.jpg is 1, and the exitcode from mkdir somedir is 0 – allard Aug 24 '13 at 02:12

2 Answers2

0

If there is an error it will to go to ErrorStream , you need to attach that one also:

BufferedReader bre = new BufferedReader
        (new InputStreamReader(p.getErrorStream()));
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • @allard check this related post : http://stackoverflow.com/questions/3343066/reading-streams-from-java-runtime-exec?answertab=active#tab-top – Juned Ahsan Aug 24 '13 at 02:22
  • as I said, i am quite a newby, but I see some light on the end of the tunnel, it's about the * , am I right? – allard Aug 24 '13 at 02:32
  • ** OK I SOLVED it... ** String [] cmds = {"bash", "-c", cmd}; ProcessBuilder probuilder = new ProcessBuilder( cmds ); – allard Oct 09 '13 at 19:58
0

When you run rm * on linux, the shell interprets and takes care of the *. In Java, that same shell isn't running, so the * isn't being interpreted as a wildcard.

As pointed here, try extracting the target/working directory out of your cmd input and do something like:

File[] files = new File(<directory>).listFiles();
for(File file : files){
  if(file.getAbsolutePath().endsWith(".jpg")){
      //perform delete
  }
}

Alternatively, you can try (not-tested, since I don't have a linux box right now):

String[] command = new String[] {"rm", "*.jpg"}
p = Runtime.getRuntime().exec(command);
Community
  • 1
  • 1
victorantunes
  • 1,141
  • 9
  • 20
  • executeCommand ("rm " + FieldGraphicsDir.getText() + "/" + "*.jpg"); is command fed into the executeCommand method – allard Aug 24 '13 at 02:23