Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java Runtime.getRunTime().exec & wildcards?

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?

like image 222
Jakob Avatar asked Jan 21 '10 18:01

Jakob


People also ask

What does runtime getRuntime () exec () do?

getRuntime(). exec() method to use the command-line to run an instance of the program "tesseract". the first argument calls the tesseract program, the second is the absolute path to the image file and the last argument is the path and name of what the output file should be.

What is Java Runtime exec ()?

exec(String[] cmdarray, String[] envp) method executes the specified command and arguments in a separate process with the specified environment. This is a convenience method. An invocation of the form exec(cmdarray, envp) behaves in exactly the same way as the invocation exec(cmdarray, envp, null).

Does Java have exec?

exec() method to call programs or commands from within your Java™ program.

What is runtime in Java?

The Java Runtime Environment (JRE) is software that Java programs require to run correctly. Java is a computer language that powers many current web and mobile applications. The JRE is the underlying technology that communicates between the Java program and the operating system.


4 Answers

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*" });
like image 123
Malvika Avatar answered Oct 03 '22 16:10

Malvika


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\"")

like image 38
Mark Bolusmjak Avatar answered Oct 03 '22 16:10

Mark Bolusmjak


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()

like image 40
Dennis Williamson Avatar answered Oct 03 '22 16:10

Dennis Williamson


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

like image 35
Richa Avatar answered Oct 03 '22 15:10

Richa