0

I wanto to execute Runtime.getRuntime().exec(); on Java to list files on some directory.

So I wanto to pass this command "ls /mnt/drbd7/i* | tail -1", but because the star the command returns null. And I realy need this star. I need to select the last file modified on the directory. I tryed to use java.io.File but it cannot get the last file.

Does anybody have a hint? Thanks in advance! Felipe

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Felipe
  • 7,013
  • 8
  • 44
  • 102
  • 1
    Some code to show how you are using `.exec()` would help. The comments on this question should help – madth3 Feb 21 '13 at 20:19
  • In a way this is a dupe of [this question](http://stackoverflow.com/q/13046789/422353) but that one was solved in a comment. – madth3 Feb 21 '13 at 20:33

4 Answers4

2

You need to pass the command through the bash shell to that it can do a glob to convert the wildcards to a file list:

Runtime.getRuntime().exec(new String[]{ "/bin/bash", "-c", "ls", "/mnt/drbd7/i*", "|", "tail", "-1"});
Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

You need to pass the command to a shell which will expand the star—and interpret the pipe symbol. You are starting not one, but two processes.

bash -c ls /mnt/drbd7/i* | tail -1
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
1

The command ls /mnt/drbd7/i* | tail -1 won't display the last modified file, since the command ls sorts the results by name, by default. You can do ls -t /mnt/drbd7/i* | head -1 instead.

You could use the answer to this question:

How do I find the last modified file in a directory in Java?

Community
  • 1
  • 1
eskaev
  • 1,108
  • 6
  • 11
  • Maybe in this case the files are being created sequentially and `ls` default behaviour is enough, but good point. – madth3 Feb 21 '13 at 20:35
  • Sorry, I expressed in a wrong way. I would say that my files have a number on its name, and it represents the date. new Date().getTime(). So if I order them I should get the last one always. Thanks for your advice anyway :) – Felipe Feb 21 '13 at 20:37
  • You are welcome. But you should not accept this answer then, since it does not really answer the question. – eskaev Feb 21 '13 at 20:41
0

Under Unix, patterns like * and ? in command line parameters are expanded by the command shells and not by the individual programs. There are some exceptions of programs that know how to handle wildcards, but ls is not one of them. The same goes for pipes: shells know how to handle them, java.lang.Runtime doesn't.

So, if you want to use these features, you would have to do something like this:

Runtime.getRuntime().exec("/bin/sh -c 'ls /mnt/drbd7/i* | tail -1'")

But note, that this is a very system-specific solution (it even depends on the current user's configuration) to a problem that can be solved with the means of pure Java (see java.io.File.listFiles, java.nio.file.DirectoryStream, etc).

Andreas Mayer
  • 687
  • 5
  • 15