0

I am trying to execute a find command using java code. I did the following:

sysCommand = "find . -name '*out*' > file1"

Runtime runtimeObj = Runtime.getRuntime();

try {
    Process processObj = runtimeObj.exec(sysCommand);
    processObj.waitFor();
    ...

This Linux command is executed when I use command line but fails in Java, why?

Tim Bender
  • 20,112
  • 2
  • 49
  • 58
Maxwell
  • 409
  • 1
  • 6
  • 19

3 Answers3

1

This question is probably a duplicate or a duplicate.

  • Anyway, you could use File.list, providing a Filter on the type of files you want. You could call it recursively to get all sub-directories. I don't love this answer. You would think there is a simpler way.

  • A friend of mine recommended Commons-Exec from Apache for running a command. It allows you to use a time out on the command. He recommended it because Runtime can have issues with large stdout and stderr.

Community
  • 1
  • 1
Jess
  • 23,901
  • 21
  • 124
  • 145
  • Would File.list work on sub directories . Like If I have files in multiple sub directories then would it work. – Maxwell Feb 16 '13 at 02:00
  • No I don't think it will find sub-dirs. There has got to be a better way than [this](http://stackoverflow.com/questions/3008043/list-all-files-from-directories-and-subdirectories-in-java). – Jess Feb 16 '13 at 02:06
  • I've included an answer that will search sub-directories using File.listFiles. I would recommend using `ProcessBuilder`, but yes, there are risks to making a sub-process in that some operating systems will hang the process if the standard output/error buffer fills. You must consume those streams. – Tim Bender Feb 16 '13 at 02:16
  • +1 because the second "duplicate" link has a helpful question body. – Tim Bender Feb 16 '13 at 02:22
1

As far as I know, it is not allowable to use any form of piping operator in Runtime.exec. If you want to move the results to a file, you will have to do that part in Java through Process.getInputStream.

Tim Bender
  • 20,112
  • 2
  • 49
  • 58
1

If you are interested in doing this in Java then you will want to do something like this:

public void find(File startDirectory, FileFilter filter, List<File> matches) {
    File[] files = startDirectory.listFiles(filter);
    for (File file:files) {
        if(file.isDirectory()) {
            find(file, filter, matches);
        } else {
            matches.add(file);
        }
    }
}

Then you need but write the FileFilter to accept directories and files that match your pattern.

Tim Bender
  • 20,112
  • 2
  • 49
  • 58