In java you can use Runtime to run programs.
Runtime.getRuntime().exec("program");
You can also use "cmd" to run command-line commands.
Then, if option parameters weren't needed, you could simply use 'start' command.
//this will open notepad in my pc
Process pr = Runtime.getRuntime().exec("cmd /c start test.txt");
If you really need to pass commands you can use some auxiliar commands and build your own command-line:
With 'assoc' you retrieve the filetype
With 'ftype' you retrieve the application for a filetype
Then:
private static String command(Runtime rt, String command) throws IOException {
Process pr = rt.exec("cmd /c " + command);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(pr.getInputStream()))){
return reader.readLine();
}
}
public static void main(String[] args) throws IOException {
//without parameters is an easy job
Process pr = Runtime.getRuntime().exec("cmd /c start test.txt");
//with parameters things get messy
Runtime rt = Runtime.getRuntime();
String out1 = command(rt, "assoc .txt");
System.out.println(out1);
String assoc = out1.split("=")[1];
String out2 = command(rt, "ftype " + assoc);
System.out.println(out2);
String app = out2.split("=")[1].split(" ")[0]; //error prone, consider using regex
command(rt, app + " /P test.txt"); //This will print (/P) the file using notepad
}
Of course, none of these are portable at all.
For more info:
Running Command Line in Java
Best way to get file type association in Windows 10 from command line?
https://www.addictivetips.com/windows-tips/file-app-association-command-prompt-windows-10/
How to open file with default application in cmd?