1

I am able to run this command in Windows PowerShell.

Add-Content -Path C:/Users/User/Desktop/sda.txt -Value "`nThis is the last line"

I tried to run the similar command via Java but it's not executing the command.

Runtime runtime = Runtime.getRuntime();
System.out.println("powershell Add-Content -Path C:/Users/User/Desktop/sda.txt -Value " + "\"`nThis is the last line\"");
runtime.exec("powershell Add-Content -Path C:/Users/User/Desktop/sda.txt -Value " + "\"`nThis is the last line\"");

Second attempt as suggested by aquaraga

Runtime runtime = Runtime.getRuntime();
Process proc;
System.out.println("powershell Add-Content -Path C:/Users/User/Desktop/sda.txt -Value " + "\"`nThis is the last line\"");
proc = runtime.exec("powershell Add-Content -Path C:/Users/User/Desktop/sda.txt -Value " + "\"`nThis is the last line\"");
try {
            proc.waitFor();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
3
  • You have to assign the return value of runtime.exec to a variable, say proc. Then perform proc.waitFor() Commented Jul 19, 2015 at 4:53
  • It is most likely waiting for a user input or erroring out. Before you waitFor(), can you print the content of the process' error stream? You can refer to this gist: gist.github.com/aquaraga/758c09eb482d1934b4bb Commented Jul 19, 2015 at 5:11
  • Add-Content simply adds a line to the end of a file; why not program that functionality entirely in Java? It would be shorter & cleaner... Commented Jul 19, 2015 at 5:20

1 Answer 1

1

Wrap the powershell command argument in a single quote:

proc = runtime.exec("powershell Add-Content -Path C:/Users/User/Desktop/sda.txt -Value " + "\"'`nThis is the last line'\"");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.