0

My problem is that, i am using Runtime.getruntime.exec() function to run my unix command on Java. But, it jumps to the end of codes while exec() command is being run. The codes are below.

    Process songProcess;
    ArrayList<String> xmlFilePathsForEmi = new ArrayList<String>();
    int countForEmiSongUpdates = 0;
    String line;
    try {
        songProcess = Runtime.getRuntime().exec(new String[]{"find /home/gozenem/emiornek/ -name '*.xml'"}); // It jumps here !
        songProcess.waitFor();
        bufferedReaderSong = new BufferedReader(new InputStreamReader(songProcess.getInputStream()));
        while((line = bufferedReaderSong.readLine()) != null){
            xmlFilePathsForEmi.add(line);
        }

...
...
...
}

I do not know what it is related to, may be there is a character that exec function could not run. I need your precious help. Thank you.

prgrmmr
  • 3
  • 2

1 Answers1

3

Your String[] parameter to Runtime.exec() is incorrect. It must be split up so that it contains one element per item (the executable must be one string, then each individual argument must come in its own string).

Try something like:

songProcess = Runtime.getRuntime().exec(new String[]{"find", "/home/gozenem/emiornek/", "-name", "*.xml"});

Also calling waitFor where you are doing isn't appropriate. You need to read the output while the process is running, otherwise you risk filling up the I/O buffers that are used between the Java VM and your process. So move that waitFor to after you've processed the output.

From the Process docs:

By default, the created subprocess does not have its own terminal or console. All its standard I/O (i.e. stdin, stdout, stderr) operations will be redirected to the parent process, [...]. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • I tried what you wrote, this time it stops when running songProces.waitFor() line. It quits from the debug process. What could cause this? – prgrmmr Aug 15 '11 at 07:48
  • remove the waitFor() at all. You do not need this when running console utility. Just read its STDOUT until it ends. – AlexR Aug 15 '11 at 08:10
  • @AlexR: I kind of agree, but "best practice" would be to call `waitFor` then `exitValue` to make sure stuff worked. `find` can return non-zero, indicating (unspecified) problems. – Mat Aug 15 '11 at 08:15
  • I am trying this but it does not work. songProcess = Runtime.getRuntime().exec(new String[]{"find", "/home/gozenem/emiornek/", "-name", "*.xml","|","wc","-l"}); How can i run this? Thank you. – prgrmmr Aug 15 '11 at 12:03
  • Remove the accept flag if it's not working. Just don't use `waitFor` at all for starters. – Mat Aug 15 '11 at 12:07