Since I like to use command line in the system administration,I realized that having GUI interface is becoming highly required more and more, so, I decided to use Java in my applications whether they are desktop (swing) or web based.
In order to achieve this(execute external scripts/commands), java provides two ways, Runtime and ProcessBuilder.
I decided to use ProcessBuilder to make jar file which one you add it to your library will offer you executing external commands as well as getting the Standard Output, Standard Error and the exit status.
Download here.
Here is how to use it..
- Add the jar command-factory.jar file to the project library
- Declare and initialize the class e.g.
- CommandFactory processFactory = new CommandFactory();
- Declare and initialize list of string e.g.
- List<String> cmd = new ArrayList<>();
- cmd.add("python");
- cmd.add("c:\\test.py");
- Set the command to be executed e.g.
- processFactory.setCmdList(cmd);
- Call execute method e.g.
- processFactory.execCommand();
- You can check the exit status
- e.g. processFactory.getExitCode();
- Standard output e.g.
- processFactory.getStdOutPut();
- Standard error e.g.
- processFactory.getStdError();
- Check the executed command e.g.
- processFactory.getCmdList();
No comments:
Post a Comment