Problem with directly and indirectly access system command through Java?
I want to list all the file and write the list to a .txt file by using Runtime from Java. And I did this :
File workDir = new File("/home/name/ghost/");
String cmd = "ls -l > data.txt";
Process pr = Runtime.getRuntime().exec(cmd, null , workDir);
it didn't work until I replace the cmd command by a shellscript:
String cmd = "./shell.sh";
开发者_StackOverflowand here is what in the shell script :
#!/bin/bash
ls -l > data.txt
exit 0
I want to ask why I can't access system command directly through Java ?
Runtime.exec
doesn't do what you think it does. In your command, it invokes "ls" with the arguments "-l", ">", and "data.txt", which is what is going wrong. It's as if you had written this:
String[] cmd = new String[] {"ls", "-l", ">", "data.txt"};
If you really wanted to invoke the shell and use the shell's redirection operator, this is easy enough, invoke the shell with your command as an argument to the shell:
String[] cmd = new String[] {"sh", "-c", "ls -l > data.txt"};
Of course you could just do it in Java, as other answers suggest.
The problem is that the >
operator is a feature of your shell, not of Java or the ls
command.
Runtime.exec
doesn't attempt to replicate any shell-like behaviour; it just attempts to execute the command you give it. Your second example works because it explicitly uses Bash to run the ls -l > data.txt
command and Bash knows how to handle >
.
It's probably better to use an approach like @whaley suggested if you can; otherwise using a shell script is likely to be the only way to get shell semantics.
I'm not even going bother answering this question as it is posed, as the same thing can be done using Java only without relying on external processes:
File dir = new File("/some/dir");
FileWriter fw = new FileWriter(new File("/some/file"));
for (File f : dir.listFiles()) {
fw.write(f.getName() + "\n");
}
fw.close();
精彩评论