13

i'm trying to remove junk files by using

Process p = Runtime.getRuntime().exec();

it works fine as long as i do not use wildcards, i.e. this works:

Process p = Runtime.getRuntime().exec("/bin/rm -f specificJunkFile.java");

while the following throws back "No such file or directory":

Process p = Runtime.getRuntime().exec("/bin/rm -f *.java");

i should be able to do all the nice things as outlined here, right?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Jakob
  • 872
  • 10
  • 26

5 Answers5

15

After a lot of searching I found this: http://www.coderanch.com/t/423573/java/java/Passing-wilcard-Runtime-exec-command

Runtime.exec(new String[] { "sh", "-c", "rm /tmp/ABC*" });
animuson
  • 53,861
  • 28
  • 137
  • 147
Malvika
  • 151
  • 1
  • 2
  • This assumes that you are running on a system for which the command interpreter `sh` is available. Which makes it somewhat non-portable. – thoni56 Oct 26 '20 at 15:09
9

Those are Bash wildcards. They are interpreted within the Bash shell. You are running rm directly, so there is no shell to interpret the * as 'all files'.

You could use bash as the command. e.g.:

Runtime.getRuntime().exec("/path-to/bash -c \"rm *.foo\"")

Mark Bolusmjak
  • 23,606
  • 10
  • 74
  • 129
  • 2
    okay i'm doing: Runtime.getRuntime().exec("/bin/bash -c \"rm *.foo\""); and i'm getting: ERROR>*.foo": -c: line 0: unexpected EOF while looking for matching `"' this i do not understand... the escapes are correct aren't they? – Jakob Jan 21 '10 at 19:38
8

Might I suggest that you let Java do this for you?

  • Use file.listFiles() to get the list of files
  • Use file.getName().contains(string) to filter them if needed
  • iterate over the array performing file.delete()

Advantage: improved portability, saves the cost of an exec()

Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
  • 2
    How do you use wild cards in general. Leave the rm etc. Let's say I have my own binary and I have to launch that from a java code. How would you do that? – harithski Aug 31 '11 at 14:58
  • 1
    The first two bullets are the handling of the `*`, the third corresponding to the `rm`. So you need to know what part of the string is a filename pattern, but otherwise you can stitch together any command line using the list of the files that you get from `listFiles()` (provided your external command accepts multiple filenames, of course). – thoni56 Oct 26 '20 at 15:14
2

Runtime.getRuntime().exec(new String[] { "sh", "-c", "gunzip *.gz" });

Richa
  • 700
  • 8
  • 12
0
  1. Use exec( String [] { cmd , arg1 , arg2...)

  2. Here's a full example to get the result as a String : Link.