Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ExecTest {
- static void exec(String cmd) throws Exception {
- Process p = Runtime.getRuntime().exec(cmd);
- int i;
- while( (i=p.getInputStream().read()) != -1) {
- System.out.write(i);
- }
- while( (i=p.getErrorStream().read()) != -1) {
- System.err.write(i);
- }
- }
- public static void main(String[] args) throws Exception {
- System.out.print("Runtime.exec: ");
- String cmd = new java.util.Scanner(System.in).nextLine();
- exec(cmd);
- }
- }
- myshell$ javac ExecTest.java && java ExecTest
- Runtime.exec: ls -l 'My File.txt'
- ls: cannot access 'My: No such file or directory
- ls: cannot access File.txt': No such file or directory
- myshell$ ls -l 'My File.txt'
- -rw-r--r-- 1 me me 4 Aug 2 11:44 My File.txt
- // Simple, sloppy fix. May have security and robustness implications
- String myFile = "some filename.txt";
- String myCommand = "cp -R '" + myFile + "' $HOME 2> errorlog";
- Runtime.getRuntime().exec(new String[] { "bash", "-c", myCommand });
- String myFile = "some filename.txt";
- ProcessBuilder builder = new ProcessBuilder(
- "cp", "-R", myFile, // We handle word splitting
- System.getenv("HOME")); // We handle variables
- builder.redirectError( // We set up redirections
- ProcessBuilder.Redirect.to(new File("errorlog")));
- builder.start();
Add Comment
Please, Sign In to add comment