Guest User

Untitled

a guest
Jun 24th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. public class ExecTest {
  2. static void exec(String cmd) throws Exception {
  3. Process p = Runtime.getRuntime().exec(cmd);
  4.  
  5. int i;
  6. while( (i=p.getInputStream().read()) != -1) {
  7. System.out.write(i);
  8. }
  9. while( (i=p.getErrorStream().read()) != -1) {
  10. System.err.write(i);
  11. }
  12. }
  13.  
  14. public static void main(String[] args) throws Exception {
  15. System.out.print("Runtime.exec: ");
  16. String cmd = new java.util.Scanner(System.in).nextLine();
  17. exec(cmd);
  18. }
  19. }
  20.  
  21. myshell$ javac ExecTest.java && java ExecTest
  22. Runtime.exec: ls -l 'My File.txt'
  23. ls: cannot access 'My: No such file or directory
  24. ls: cannot access File.txt': No such file or directory
  25.  
  26. myshell$ ls -l 'My File.txt'
  27. -rw-r--r-- 1 me me 4 Aug 2 11:44 My File.txt
  28.  
  29. // Simple, sloppy fix. May have security and robustness implications
  30. String myFile = "some filename.txt";
  31. String myCommand = "cp -R '" + myFile + "' $HOME 2> errorlog";
  32. Runtime.getRuntime().exec(new String[] { "bash", "-c", myCommand });
  33.  
  34. String myFile = "some filename.txt";
  35. ProcessBuilder builder = new ProcessBuilder(
  36. "cp", "-R", myFile, // We handle word splitting
  37. System.getenv("HOME")); // We handle variables
  38. builder.redirectError( // We set up redirections
  39. ProcessBuilder.Redirect.to(new File("errorlog")));
  40. builder.start();
Add Comment
Please, Sign In to add comment