0

I have a program which opens a command line session in which inserts 2 words. To read these words i've previously used a batch script with the following command : echo word1=%1 word2=%2 >> C:\abc.txt. Now i have to do that with Java.

Do you have any ideas how could I put this command cmd.exe /C echo user=%1 pass=%2 >> C:\abc.txt in Java ProcessBuilder?

I've tried ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C echo user = '%1' password = '%2' >> \"C:\\abc.txt\""); but without success.

After I run my java app the content of abc.txt is user = '%1' password = '%2' but it should be something like that: user = John password = Doe . Thank you in advance !

pandoJohn
  • 1
  • 3

1 Answers1

0

You need to use the String[] args to access your command line parameters when you invoke your java app. Its not the same as in Windows Batch files. Something like this:

public static void main(String[] args) {
    ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C echo user = '" + args[0] + "' password = '" + args[1] + "' >> \"C:\\abc.txt\"");
}

Another approach would be to use environmental variables, where prior to running your command you do the following:

  1. Define your environmental variables before executing the jar/class file:
set user="craig"
set password="swordfish"
  1. Look up the properties in your class:
public static void main(String[] args) {
    final String user = System.getProperty("user");
    final String password = System.getProperty("password");
    final String command = "/C echo user = '" + user + "' password = '" + password + "' >> \"C:\\abc.txt\"";
    ProcessBuilder pb = new ProcessBuilder("cmd.exe", command);
}
Craig
  • 2,286
  • 3
  • 24
  • 37
  • I am not allowed to pass args to that class. I have to implement that command line specific command in java. After that I will export my class in a jar file and I will run him from a batch script. %1 and %2 are used to read two values which are already present in a command line session. I hope now it's clearer. – pandoJohn Aug 31 '15 at 10:57
  • @Jean.C I've updated my answer to include an example which uses environmental variables. This should work since you cannot pass the `args` via the `main()` method. – Craig Aug 31 '15 at 11:10
  • Thanks a lot for your time but unfortunately this doesn't help me. Please take a look at my updated question - maybe it's clearer now. – pandoJohn Aug 31 '15 at 11:43
  • Yeah I think I understand what you're doing now. Take a look at this question: http://stackoverflow.com/a/2144201/529256. You may need to put your command in a batch file which then points to the arguments, which you pass as arguments to `ProcessBuilder`. – Craig Aug 31 '15 at 11:55