Hello there!I am using ubuntu linux o/s. I want to make a program that can execute other programs via system calls. Is there any way to accomplish that with java?
Printable View
Hello there!I am using ubuntu linux o/s. I want to make a program that can execute other programs via system calls. Is there any way to accomplish that with java?
Have you looked at using Runtime.getRuntime() and then calling exec on the Runtime object returned?
I've always used the ProcessBuilder class to run programs. It allows you to run a program (including any arguments). Then, you can optionally wait for the process to end.
Sure. Just know that I'm on a windows machine, so if you are not, this won't work (you'll need to change the program to something else) - the programs available (and their paths) aren't system independent.
This is a simple example which opens a file in notepad (by passing a pathname as an argument). If you passed no arguments, it would open notepad, with an empty file.
Code:import java.io.IOException;
public class RunNotepad
{
/**
* Main method
*
* @param args
* (not used)
*/
public static void main(String[] args)
{
// File to open in notepad
String pathname = "c:\\test\\test.txt";
/*
* No path is necessary, since notepad is part of the PATH (by default)
* (any program that is in a folder, which is part of the Windows PATH
* environment variable can be started without specifying the directory)
*
* You can pass arguments as parameters as well. For example, passing
* a filename will open that file in notepad.
*
* Note that you don't need to surround an argument in quotes, even if
* it contains a space.
*/
ProcessBuilder notepad = new ProcessBuilder("notepad", pathname);
try {
// Start notepad
Process process = notepad.start();
// Wait for notepad to be closed
process.waitFor();
System.out.println("Congratulations you just started and closed notepad.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}